开发者

Conditional operator "?:" in C++

Why this statement :

int a = 7, b = 8, c = 0;
c = b > a? a > b? a++: b++: a++ ? b++:a--;
cout << c;

is not equal to :

int a = 7, b = 8, c = 0;
c = (b > a? (a > b? a++: b++): a++)? b++: a--;
cout << c;

and is equal to :

int a = 7, b = 8, c = 0;
c = b > a? (a > b? a++: b++): (a++? b++: a--);
cout << c;
开发者_StackOverflow中文版

Please give me some reason. Why ?


Operator precedence and associativity

Table of operator precedence and associativity for C++


Just put it on multiple lines to see the differences :

c = b>a        // true
    ? a>b      // false
      ? a++
      : b++    // b is incremted = 9; c = 8 (post increment)
    : a++ 
      ? b++
      : a--;

is not equal to :

c = ( b>a     // true
    ? ( a>b   // false
      ? a++
      : b++ ) // b is incremted = 9
    : a++ )   // a = 7 (= 8 after post increment), thus true
    ? b++     // ... b is incremented = 10, c = 9 (post increment)
    : a--;

and is equal to :

c = b>a         // true
    ? ( a>b     // false
      ? a++
      : b++ )   // b is incremnted = 9, c = 8 (post increment)
    : ( a++     
        ? b++   
        : a-- );


Also, please note that these (horrible) expressions are deterministic only because the ?: operator is used. This operator is one of the very few operators in the C language where the order of evaluation is actually specified. Had you written some other abomination like i++ + ++i; then the compiler could have evaluated the left operand or the right operand first, which it picks is not defined in the C language.

As a rule of thumb, never use the ++ operator as part of an expression with other operators. Only use it on a line of its own (or as loop iterator). Because, against mainstream belief, there is actually never a reason to use it together with other operators.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜