operator precedence

Feb 15, 2016 at 8:24am
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).
Feb 15, 2016 at 8:29am
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 Feb 15, 2016 at 8:49am
Feb 15, 2016 at 8:54am
But it still gives me answer on both cpp.sh and MS VC++, i.e. 8.
Feb 15, 2016 at 9:19am
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 Feb 15, 2016 at 9:20am
Feb 15, 2016 at 9:28am
thanks a lot Peter
Topic archived. No new replies allowed.