0

Here is a program

#include<stdio.h>
int main()
{
int i=2;
printf("I=%d i=%d\n",++i,++i);
}

The output I got was

4 4 

it is a bit surprising output to me. How does that ++i works? and why is that giving 4 4 and not 3 4 in result?

Just read it ,it is different from the thread which you people are marking it as duplicate.

Registered User
  • 5,173
  • 16
  • 47
  • 73
  • 1
    Questions like this have been asked *a lot* on this site. You should make a point to search for existing questions before you ask a new one. – Jon Purdy Jun 20 '11 at 08:37
  • shame on people who closed it without even understanding what the problem was. – Registered User Jun 20 '11 at 08:56
  • I didn't vote to close, for what it's worth. Anyway, the point is that answers to this question are essentially the same as those to existing questions: namely, that reading and writing a variable without an intervening sequence point is undefined behaviour, and the compiler is allowed to do whatever it wants. – Jon Purdy Jun 20 '11 at 09:01
  • The issue is exactly the same, even if the program is slightly different. You're modifying (and reading) `i` twice in the same instruction (precisely speaking, you're modifying `i` twice with no intervening sequence point). See also [C programming: is this undefined behavior?](http://stackoverflow.com/questions/3450582) with a similar example where `i` is written once and read twice. – Gilles 'SO- stop being evil' Jun 20 '11 at 16:32

1 Answers1

2

Undefined behavior. You shouldn't change value of the variable and read it multiple times in the same sequence point.

littleadv
  • 20,100
  • 2
  • 36
  • 50