1

I'm new to C language so please sum1 help me out. A C code written

int i=3;
printf("%d",++i + ++i);

Complier gives O/P =9. How?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Brite Roy
  • 425
  • 3
  • 9
  • 28

1 Answers1

4

The results are undefined. You're modifying a variable more than once in an expression (or sequence point to be more accurate).

Modifying a variable more than once between sequence points is undefined, so don't do it.

It might be your compiler, for this particular case decides to evalate ++i + ++i as

  • increment the last ++i , yielding 4, leaving i to be 4
  • increment the first ++i, yielding 5, leaving i to be 5 (as the prior step left i as 4, incrementing it to 5)
  • sum the two values, 4 + 5.

Another compiler, or if you alter the optimization level, or if you change the code slightly, might produce different output.

Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506
  • agreed: I checked my gcc 4.1.2 and recv'd the value 10 (which could be just as easily explained as your 9) – KevinDTimm Sep 28 '10 at 13:28
  • @KevinDTimm could you please explain how would you account for `10`? – ajay Mar 25 '14 at 19:49
  • @ajay - yes, the standard says that this results in undefined behavior. So, any result is equally (in)valid. – KevinDTimm Mar 25 '14 at 19:59
  • @KevinDTimm Yes, it is undefined behaviour and anything can happen because the standard imposes no requirement on the implementation. I was just wondering about `which could be just as easily explained as your 9` part in your comment. – ajay Mar 25 '14 at 20:07