tags:

views:

211

answers:

5

What must this code segment return ? 16 16 16 right ?

int main(int argc,char *argv[])
{
   int a=2,*f1,*f2;
   f1=f2=&a;
   *f2+=*f1+=a+=2.5;
   printf("%d %d %d\n",a,*f1,*f2);
   return 0;
}

strangely, it returns 8 8 8 to me ???? :-(

+3  A: 

*f2+=*f1+=a+=2.5;

Same old Undefined Behaviour.

Prasoon Saurav
@Prasoon: if, as I am beginning to suspect, you've written a bot to scan the new questions for instances of this, and rapidly alert you to the opportunity to get in quick for loads of points, then you should totally submit it to GCC for use issuing warnings about dodgy code ;-)
Steve Jessop
@Steve : Made it CW [No more reps on this one now].
Prasoon Saurav
@Steve: no, probably he is just teaching C to all those guys, and they all listen well at the beginning of the course when he is telling them that SO is a wonderful place to get all the answers, and then part of them slowly fall asleep when he teaches them UB.
Jens Gustedt
@Steve : And now I have decided not to post answers to these kind of questions.
Prasoon Saurav
@Prasoon: Sorry, I didn't intend it as any kind of criticism. I think it's good that you answered: people need to be told this kind of thing before they spend a lot of time being very wrong about what UB actually is, like you dealt with last time. So you deserve the upvotes you get for doing it. I was just trying to joke that you got to the last couple so quickly. I was reminded of an old colleague who had a program scanning his email for the word "biscuit" (US: "cookie") and popping up an alert on screen.
Steve Jessop
@Steve : Its all right Steve `:)` [I noticed the smiley :)]. I think I have posted too many answers for these kind of questions lately so I should probably focus more on other stuffs too. No need to be sorry, its perfectly fine, no hard feelings from my side :)
Prasoon Saurav
+3  A: 

It's undefined behavior because the value of a is modified more than once in that string of assignments. So what you might expect is meaningless.

Michael Burr
+3  A: 

This is undefined behavior according to spec 6.5/2 because you modify an object more than once between sequence point:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

czchen
And because the behavior is undefined, *any* result is possible, whether it appears to make sense or not.
John Bode
A: 

It seems that it's translated to

*f2 += 2;
*f1 += 2;
  a += 2.5;

and that += is not so transitive as =.

ruslik
It is essentially the same as "a += a += a += 2.5" and that's pretty much well into nasal demon territory.
Vatine
+2  A: 

For an actual understanding of the issue here try comp.lang.c FAQ article on sequence points.

Tomasz Łazarowicz