0

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

I found this piece of code, originally here:

#include <stdio.h>

int main()
    {
    int p = 0;
    p = p++ + ++p;
    printf("p=%d\n", p);

}

I guessed the output will be 2, but when I compiled the code and I execute it, the output was 3, why?

Community
  • 1
  • 1
SIFE
  • 5,567
  • 7
  • 32
  • 46
  • http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc – Mysticial Apr 03 '12 at 01:38
  • just to be sure: are you looking for an explanation for the output for this undefined behavior? – cctan Apr 03 '12 at 01:42
  • Read the assembly code generated by your compiler. – Greg Hewgill Apr 03 '12 at 01:44
  • Please try searching to see if a question has already been asked (time and time again) before asking it! – Jonathon Reinhart Apr 03 '12 at 01:47
  • @JonathonReinhart Um... what search term would you use? Assume you are a beginner and you know nothing about undefined behavior. – Mysticial Apr 03 '12 at 01:54
  • @Mysticial Good point. I tried just now and it was quite difficult. Still voting to close, but I'll delete the comment. – Jonathon Reinhart Apr 03 '12 at 01:58
  • 1
    @JonathonReinhart These are one of the few dupe questions that (although annoyingly common), I will not downvote because they're almost impossible to search for. So I just close as dupe and move on. – Mysticial Apr 03 '12 at 02:01

1 Answers1

6
p = p++ + ++p;

is undefined behaviour. Read about Sequence point.

P.P
  • 117,907
  • 20
  • 175
  • 238