Because a conditional-operator expression, unlike an if
statement, produces a value, you can place it inside another
expression. In the following, for example, a
conditional-operator expression appears inside an output
expression, solving the duplication problem encountered in
Segment 285:
#includemain ( ) { int change; cin >> change; cout << "The temperature has changed by " << change << (change == 1 ? " degree" : " degrees") << endl; } --- Data --- 1 --- Result --- The temperature has changed by 1 degree
If the change is 1 degree, the value returned by the
Boolean expression, and displayed, is
"degree"
; otherwise, the value returned, and
displayed, is "degrees"
.
Note that the parentheses surrounding the Boolean expression are absolutely necessary, because the output operator has precedence higher than that of the conditional operator.