Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question about ? and : 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;

Please give me some reason. Why ?

like image 971
assembler Avatar asked May 09 '10 11:05

assembler


3 Answers

Because ? : is right-to-left associative. It's defined like that in the language.

like image 165
sth Avatar answered Oct 26 '22 07:10

sth


I believe @sth has provided the correct answer, however, I think @Skilldrick got it right on the comments - why the hell would you ever write something like that.

As well as the precedence issue, you really need to be careful when incrementing the same variables in a single statement. There may or may not be sequence points in the statement, and therefore the order of evaluation of the increments might not be guaranteed. You could end up with different results with different compilers or even different optimization settings on the same compiler.

like image 21
Paul Tomblin Avatar answered Oct 26 '22 06:10

Paul Tomblin


The operators &&, ||, and ?: perform flow control within expressions. ?: behaves like an if-else statement.

c = b>a?a>b?a++:b++:a++?b++:a--;

if ( b>a )
    if ( a>b )
        a ++;
    else
        b ++;
else if ( a ++ )
    b ++;
else
    a --;

b>a? (
    a>b ?
        a ++
    :
        b ++
) : ( a ++ ?
    b ++
:
    a --
)

The associativity is necessary to have behavior like if … else if … else.

Sometimes I use an expression similar to yours for lexicographic sequence comparision:

operator< ()( arr &l, arr &r ) {
    return l[0] < r[0]? true
         : r[0] < l[0]? false
         : l[1] < r[1]? true
         : r[1] < l[1]? false
         : l[2] < r[2];
}
like image 23
Potatoswatter Avatar answered Oct 26 '22 06:10

Potatoswatter