3

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

There is a code following below and i ma facing a very serious problem in understanding the logic for the code.

#include <stdio.h>
#include <stdlib.h>

int main(void )
{
int i = 1 ;
printf("\n%d %d %d %d\n",++i,i++,i++,++i) ;
return 0 ;
}

I am using gcc compiler under the linux distro named Mandriva. In the above mentioned i have used pre and post increment with a variable in the printf statement. The output that i am supposed to get is 2 2 3 5, but i am getting a different output. Please help me in this code.

I am feeling much difficult in this code.

Community
  • 1
  • 1
Rajan Chennai
  • 145
  • 1
  • 7

1 Answers1

8

It's undefined behavior. There's no sequence points between the increments of i.

Any result is a correct result (including your hard drive being formatted).

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • The hard drive being formatted is not a valid result of this code. It is only undefined regarding the evaluation order. – Emil Vikström Nov 26 '12 at 07:24
  • Does it really matter for integers if we do `++i` or `i++`? I thought this is the same. It only differs when we post-increment or pre-increment an object.. then in the first case it is modified and evaluated and in the second case it is copied and then modified. What am I missing? – Maroun Nov 26 '12 at 07:26
  • K Grigore. But is this undefined behaviour because of the version of the compiler or with the version of the OS distro we were using? What is the compiler that i can depend on? Is there any chances that we can change the behaviour of the compiler? – Rajan Chennai Nov 26 '12 at 07:26
  • @Raj89 no you can't. It's undefined because the standard says it's undefined. Just don't do it. – Luchian Grigore Nov 26 '12 at 07:30
  • And also what does formatting the hard drives has to do with the result? Please tell me clearly. – Rajan Chennai Nov 26 '12 at 07:31
  • @Raj89 undefined behavior means *anything* can happen. The "format your hard drive" was a joke (although theoretically, it could happen) – Luchian Grigore Nov 26 '12 at 07:32
  • K Grigore. I understand. Thanks anyway. Another thing. Does this same code vary compiler to compiler? – Rajan Chennai Nov 26 '12 at 07:33
  • @Raj89 you don't seem to understand. The code isn't guaranteed to give the same result every time even on the same compiler. – Luchian Grigore Nov 26 '12 at 07:34
  • S... I understand that Grigore. But there are variety of compilers and does that variety of compilers gall share the same undefined behaviour? – Rajan Chennai Nov 26 '12 at 07:47
  • @Raj89 yes. Undefined behavior is part of the language, it doesn't care what compiler you use. – Luchian Grigore Nov 26 '12 at 07:48
  • @LuchianGrigore : I was thinking about the same program. how would you determine it is an undefined behaviour??? – Bhavik Shah Dec 25 '12 at 07:11