4 The conditional expression

The rest of the module makes use of the condition expression quite a bit. This is a good time to refresh your knowledge of the conditional expression.

x = c ? v1 : v2 is the same as the following code:

 
1if (c) x = v1; 
2else x = v2;

The conditional expression is right associative. This means that the implicit parantheses groups from right to left. Let us consider the following chained conditional expressions.

c1 ? t1 : c2 ? t2 : c3 ? t3 : f3

It is the same as the following:

c1 ? t1 : (c2 ? t2 : (c3 ? t3 : f3))

This means the expression

x = c1 ? t1 : c2 ? t2 : c3 ? t3 : f3

has the same meaning as the following code:

 
1if (c1) 
2{ 
3  x = t1; 
4} 
5else 
6{ 
7  if (c2) 
8  { 
9    x = t2; 
10  } 
11  else 
12  { 
13    if (c3) 
14    { 
15      x = t3; 
16    } 
17    else 
18    { 
19      x = f3; 
20    } 
21  } 
22}

The above code is also commonly written as follows to save space.

 
1if (c1) x = t1; 
2else if (c2) x = t2; 
3else if (c3) x = t3; 
4else x = f3;