tags:

views:

105

answers:

3

Hi!

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.

+2  A: 

There's a reason for the warning... The evaluation order between sequence points is unspecified.

Matthew Flaschen
Evaluation order between sequence points is *unspecified*. "Undefined" is a bit stronger term, and means that the standard doesn't specify anything about the behavior of any part of the program.
Jerry Coffin
+1  A: 

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.

anon
A: 

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++;  
caf