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.
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:
a += 1
(since 1
is true) sets a
to 2
.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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With