operator precedence

Can anybody explain (step by step) to me why the following program output 8? I was expecting 3 as the output.


int main()
{
int a=5,b=2,c=9,d=1;
b*=!d+b-(a==5||--b)+(c=3);
cout<<b<<endl;
return 0;
}

PS: I'm not that naive in programming. 8 is the possible output only if b retains it's value as 2 but I think it has already decremented to 1 in (a==5||--b).
The result of that line is simply undefined. You are not allowed to modify a variable twice in the same expression like you do.

If you use the GCC compiler with the -Wall flag (very much recommended) it even warns you about it.

GCC wrote:
warning: operation on ‘b’ may be undefined [-Wsequence-point]

https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
Last edited on
But it still gives me answer on both cpp.sh and MS VC++, i.e. 8.
Yes, but the C++ language doesn't guarantee what the result will be. It probably just happened to be 8 because the compiler does it in a certain way, but this is nothing you should rely on. Things like this might change when you modify your code or use different compiler settings.
Last edited on
thanks a lot Peter
Topic archived. No new replies allowed.