1

Possible Duplicate:
FAQ : Undefined Behavior and Sequence Points

Different outputs on different compiler? Is this true that certain statements can generate different outputs on different compilers. I have two compilers handy gcc and msvc expression edition. When I tried a code sample on both of them I was shocked to see different outputs on them.

This was the code sample.

#include<stdio.h>
int main(void)
{
int variable_a = 100;
printf("%d %d", ++variable_a, variable_a++); return 0;
}

Output that I got on gcc was 102 100
On msvc I got 102 101.
Why such a difference?

Community
  • 1
  • 1
Shruti
  • 21
  • 2
  • 2
    "undefined behavior". http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc – kennytm Nov 15 '10 at 09:15
  • 1
    The very fact that you bothered to type in the program suggests you had reason to suspect this, or were following a tutorial that should have proceeded to explain it - so why shocked? – Tony Delroy Nov 15 '10 at 09:20
  • i am in the learning stage and i like checking the outputs on more than one compilers. the outputs were different so thoght of asking here. – Shruti Nov 15 '10 at 09:23
  • why is this undefined behavior KennyTm??? – Shruti Nov 15 '10 at 09:24
  • it's undefined simply because the language spec doesn't define unambiguously what a compiler can do there, hence there is no single correct output. – Andrzej Doyle Nov 15 '10 at 09:32

2 Answers2

4

You invoke undefined behaviour by incrementing a more than once. Any compiler would be within their rights to break into your house and beat you with a stick.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
Puppy
  • 144,682
  • 38
  • 256
  • 465
1

There are various subtle effects of this kind where the language is explicitly undefined. There's a lot of history behind why the language leaves these corners undefined. From the coder's point of view we need to avoid certain patterns such as the one you stumbled across.

See this reference for some explanation

djna
  • 54,992
  • 14
  • 74
  • 117