1

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.

darsie
  • 147
  • 6
  • 4
    Mutating a variable twice between sequence points is undefined behavior. So is mutating the variable, and then reading its value. No matter what value you expect to get as a result, it is an invalid assumption. You should just rewrite the code to be standard-conformant. – Pavel Minaev Jun 04 '10 at 21:24
  • Duplicate of [Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc...)](http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc) – Matthew Flaschen Jun 04 '10 at 21:25
  • 4
    The result is, as your compiler diagnosed, undefined. So don't write code like that. –  Jun 04 '10 at 21:26
  • Thanks Matthew for your link which made me read and understand http://en.wikipedia.org/wiki/Sequence_point and Pavels comment. – darsie Jun 04 '10 at 21:49

3 Answers3

2

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

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 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 Jun 04 '10 at 22:01
2

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.

1

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
  • 233,326
  • 40
  • 323
  • 462