Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional operator usage

Tags:

c++

Consider the following statement. What will be the value stored in b?

int a=1;
int b = a+=1 ? a+=1 : 10;

I get the answer as 4. Can anyone explain how that works please.

like image 689
shreedhar Avatar asked Jan 08 '11 04:01

shreedhar


1 Answers

It has to do with precedence. If you examine the following code (with the rightmost a+=1 changed for simplicity):

#include <iostream>

int main (void) {
    int a=1;
    int b = a+=1 ? 7 : 10;
    std::cout << b << std::endl;
    return 0;
}

you will see that the output is 8, not 7 or 10.

That's because the statement:

    int b = a+=1 ? 7 : 10;

is being interpreted as:

    int b = (a += (1 ? 7 : 10));

Now, applying that to your case, we get:

    int b = (a += (1 ? a += 1 : 10));

and, in order of execution:

  • the rightmost a += 1 (since 1 is true) sets a to 2.
  • the leftmost a += 2 (2 is the result of the previous step) sets a to 4.
  • b = 4 (4 is the result of the previous step).

Just keep in mind that you can't necessarily rely on that order of evaluation. Even though there is a sequence point at the ? (so that 1 is evaluated fully before continuing), there is no sequence point between the rightmost a += ... and the leftmost a += .... And modifying a single variable twice without an intervening sequence point is undefined behaviour, which is why gcc -Wall will give you the very useful message:

warning: operation on ‘a’ may be undefined

That fact that it gives you 4 is pure coincidence. It could just as easily give you 3, 65535 or even format your hard disk to teach you a lesson :-)

like image 101
paxdiablo Avatar answered Oct 19 '22 23:10

paxdiablo