|
Making choices in expressions
Expression a ? b : c
starts by evaluating expression a.
If a is true (or nonzero), then
a ? b : c yields the value of
expression b (and does not
compute c at all). If a is false (or 0),
a ? b : c yields the value
of expression c (and does not compute b at all).
For example,
int m = x > 0 ? x : -x;
creates variable m and stores the absolute value of x into m.
Only use this for expressions, not for statements. The coding standards require that. |
Example: finding the larger of two numbers, version 3
// maximum(x,y) returns the larger of x and y. // If x and y are equal, it returns that shared value. // Examples: // maximum(1,5) = 5 // maximum(3,2) = 2 // maximum(4,4) = 4 int maximum(const int x, const int y) { return x > y ? x : y; } |
Write a statement that makes m equal to 3n+1 if n is odd and to n/2 if n is even. Use a conditional expression. Answer
|