0

I have encountered a sorcery today.

http://codepad.org/VW2vTpWw

Language: C

Code:

#include <stdio.h>

main()
{
    int i = 5;
    i = i++;
    printf ("%i", i);
}

Output:

6

How? Why?

This is supposed to be tricky code but the other way around. The negligent programmer would think that i = i++ is just simple increment but it's not. Yet it works like one here. It's supposed to be 5! Like in JavaScript.

What should be happening.

  1. i gets the value of 5.
  2. i++ returns 5.
  3. i is post incremented by i++ (to 6).
  4. i gets the value of 5 (returned by i++).
  5. the value of i (5) gets printed.

Yet it is 6.

I haven't been able to find a description to this on SO, or the whole internet (just the other way around).

What is broken here?

Please explain.

vinczemarton
  • 7,756
  • 6
  • 54
  • 86

1 Answers1

11

It is undefined behavior to store more than once to an object without an intervening sequence point.

In particular, your step 3 and 4 have no defined ordering, the increment (and store) or the store could happen first.

luser droog
  • 18,988
  • 3
  • 53
  • 105