0

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

int main()
{
int a,b=3;
a=(b++)*(b++)*(b++);
printf("%d %d",a,b);
}

a becomes 27 but b is 6 after the execution of the expression. Can anyone tell me how the expression is executed?

Community
  • 1
  • 1
karthik
  • 41
  • 2
  • 1
    possible 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), [Undefined Behavior and Sequence Points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – Mysticial Sep 06 '12 at 15:45
  • 3
    No one can tell you because it's undefined behavior. Please search SO for the many many other similar questions. – Jim Balter Sep 06 '12 at 15:46
  • Welcome to Stack Overflow. Unfortunately for you, this question is a minor variant on a very commonly asked question — which is why your question will be closed. You will find quite a lot of similar questions which are also closed as duplicates. – Jonathan Leffler Sep 06 '12 at 15:49
  • From a mathematical perspective, it would seem that the `b++` increments are not carried out until after the line `a=(b++)*(b++)*(b++);` is executed. All three increments are then carried out simultaneously hence why `b=6` when the next line is executed. – Ren Sep 06 '12 at 15:49
  • Given your results, it has been evaluated *on this occasion* as `a = b * b * b; b += 3;`. In other words the compiler has placed all of the modifications of `b` at the end of the statement, after `a` has been calculated. You could perhaps examine a disassembly to confirm this, and play around with optimization options to see if you can provoke some other result. If that seems an incorrect result to you, well, that's what you get for writing code with undefined behavior, the compiler wastes your time trying to work out what's going on ;-) – Steve Jessop Sep 06 '12 at 15:49
  • @steve Am I right in thinking that the answer won't always evaluate in this way then when recompiled? – Ren Sep 06 '12 at 15:55
  • 1
    @Ren: The standard says that behavior is undefined, which means it's not even guaranteed to always evaluate this way each time you run the same executable, let alone recompiling it. In practice, you'll probably see that the same compiler with the same options will produce a consistent result, and some compilers will produce a consistent result for certain statements like this regardless of options. You're just not allowed to rely on that. – Steve Jessop Sep 06 '12 at 16:11
  • if a=(++b)*(++b)*(++b) then output is a=150 b=6 – karthik Sep 06 '12 at 16:35
  • @user1619903: so in that case it appears to have computed 5*5*6 -- of the three reads of `b`, two of them were after two of the increments, and the other one was after all three. Got to love that crazy undefined behavior. – Steve Jessop Sep 06 '12 at 16:38

0 Answers0