Reputation: 83
Can anyone explain me the output of the following. I tried to reason everything and can explain the later part where 'x' is assigned the value of the expression but cannot understand how the answer is different in a printf statement!!!
Different compilers might behave differently. It would be great if someone could explain this behavior for any compiler.
I am using gcc (SUSE Linux) 4.6.2 on openSUSE 12.1 (Asparagus) (i586)
code :
#include<stdio.h>
int main()
{
unsigned int x=0;
printf("expr= %d x=%d\n",(x^x),x);
printf("x=%d\n",x);
x=0;
printf("expr= %d x=%d\n",(x^x)||x++,x);
printf("x=%d\n",x);
x=0;
printf("expr= %d x=%d\n",(x^x)||x++||++x,x);
printf("x=%d\n",x);
x=0;
printf("expr= %d x=%d\n",(x^x)||x++||++x||x++,x);
printf("x=%d\n",x);
x=0;
printf("expr= %d x=%d\n",x++,x);
printf("x=%d\n",x);
x=0;
printf("expr= %d x=%d\n",++x||x++,x);
printf("x=%d\n",x);
x=0;
printf("expr= %d x=%d\n",x++||++x||x++,x);
printf("x=%d\n",x);
x=0;
printf("expr= %d x=%d\n",(x^x)||x++||++x||x++,x);
printf("x=%d\n",x);
x=0;
(x^=x);
printf("x=%d\n",x);
x=0;
(x^=x)||x++;
printf("x=%d\n",x);
x=0;
(x^=x)||x++||++x;
printf("x=%d\n",x);
x=0;
(x^=x)||x++||++x||x++;
printf("x=%d\n",x);
return 0;
}
output :
expr= 0 x=0
x=0
expr= 0 x=1
x=1
expr= 1 x=2
x=2
expr= 1 x=2
x=2
expr= 0 x=1
x=1
expr= 1 x=1
x=1
expr= 1 x=2
x=2
expr= 1 x=2
x=2
x=0
x=1
x=2
x=2
Thanks
Upvotes: 0
Views: 886
Reputation: 145899
printf("expr= %d x=%d\n",(x^x)||x++||++x,x);
This function shows unspecified behavior. The order of evaluation between (x^x)||x++||++x
and x
is unspecified.
Most of the other printf
calls in your program have the same issue.
(C99, 6.5.2.2) "The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call."
A program whose output depends on unspecified behavior is not a strictly conforming program (see C99, 4.p5).
Upvotes: 3
Reputation: 272687
You are invoking unspecified behaviour.
In an expression like func(a,b)
, the C standard does not specify which argument should be evaluated first; the compiler is free to do either.
So now consider func(x++,x)
; it is unspecified whether it is equivalent to this:
a = x++;
b = x;
func(a,b);
or this:
b = x;
a = x++;
func(a,b);
Upvotes: 4