0

Possible Duplicate:
Undefined Behavior and Sequence Points

What is the outcome of the following code:

#include <stdio.h>
int main() {
  int a = 3;
  a= (a = 2) + (a = 3);
  printf("%d", a);
}

Why do I get 6 as the output on gcc? Why not 5?

Community
  • 1
  • 1
user724619
  • 287
  • 1
  • 5
  • 8
    I'm getting **really** sick of these kinds of questions. – Billy ONeal Apr 25 '11 at 02:56
  • 1
    http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – Prasoon Saurav Apr 25 '11 at 02:57
  • gcc 4.5.2 prints 6, clang 2.9 prints 5. Sun C on a sparc prints 6. The original PDP-11 C compiler on UNIX 7 (in an emulator) prints 5. Other compiles may do something altogether different, like the answers said, it's undefined. – Cubbi Apr 25 '11 at 03:34

2 Answers2

9

You're both writing and reading variable a between sequence points, so the result is formally undefined behavior.

Looking at the assembly code generated by your particular compiler will make it clear why you get a particular result, but the standard makes no guarantees at all.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 1
    The attack of the nasal demons! – C. K. Young Apr 25 '11 at 02:47
  • Nit pick: "You're both writing and reading" falsely implies that it's the combination that's fatal. Just the two assignments to `a` constitute undefined behaviour, given no intervening sequence points. – Tony Delroy Apr 25 '11 at 02:51
  • @Tony: There's more than one combination that produces undefined behavior (and unfortunately more than one applicable to this code). My saying that a read and write is bad should not be inferred to mean that things that aren't a read and write are necessarily good, that's called an inverse logic fallacy. – Ben Voigt Apr 25 '11 at 04:28
  • My point is that when you specifically offer an explanation for C of the form: A & B -> C, leaving the reader to guess at what they'd have to change to correct the code, it's inviting them to fall afoul of that fallacy.... – Tony Delroy Apr 25 '11 at 04:53
0

Because the order of operations in "a= (a = 2) + (a = 3);" is implementation-dependent. If it was "a= (a = 2) + (b = 3);" the answer would be 5. It is possible that a super-exact reading of the spec may require that the answer be 5 (if the result of an assignment is the RHS of the equation and not the LHS)... but even if it is, you should never even consider relying on anything approaching this.

jesup
  • 6,765
  • 27
  • 32
  • It couldn't be 5, maybe you mean 4? – Blindy Apr 25 '11 at 03:10
  • Read the comments to the question - quite a few compilers produce 5 as an answer, and it's not surprising. And there was no need to vote down my response... though I don't actually care in this instance – jesup Apr 25 '11 at 18:31