Reputation: 147
I want the following code to print 11, but prints 12, except in the last case, where it prints 10.
x=5; x1=x+(x=6); printf("%d\n",x1);
x=5; x1=(x=x)+(x=6); printf("%d\n",x1);
x=5; x1=(x+0)+(x=6); printf("%d\n",x1);
x=5; x1=(x=5)+(x=6); printf("%d\n",x1);
x=5; x1=(x=6)+x; printf("%d\n",x1);
x=5; x1=(x=6)+(x=x); printf("%d\n",x1);
x=5; x1=(x=6)+(x+0); printf("%d\n",x1);
x=5; x1=(x=6)+(x=5); printf("%d\n",x1);
gcc says in every case: 'warning: operation on ‘x’ may be undefined'.
That's mean.
Bernhard
PS: There's no question, sorry. Thanks for your answers. :)
PPS: Actual code is:
while ( data-(data=read(adr)&(1<<6)) ) i++;
I'm waiting for bit 6 at adr to stop toggling.
Upvotes: 1
Views: 671
Reputation: 239051
You can use the little-used comma operator, along with another variable, in order to write the loop you wanted:
while ( lastdata = data, lastdata != (data = read(adr) & (1<<6)) ) i++;
Upvotes: 1
Reputation: 284836
There's a reason for the warning... The evaluation order between sequence points is unspecified.
Upvotes: 2
Reputation:
The results are undefined, no further explanation necessary. But to explain two possible ways the compiler could treat your code:
int x = 1;
int n = (x=3) + x;
The compiler can evaluate (x=3) first in which case the assignment to n has the value 6. Or it can evaluate x first, in which case the assignment to n has the value 4.
Upvotes: 2