-1

What is the way of working out:

int i=5;
a= ++i + ++i + ++i;

If we go by normal right to left evaluation, the result should be 21 (6 + 7 + 8) .

I remember studying in school, that the answer was 24(8 + 8 + 8)

But I tried it on CodeBlocks, www.ideone.com, ie gcc 4.8.1 compiler and now I get 22. Could someone please explain the reason

Ankit Aggarwal
  • 2,367
  • 24
  • 30

2 Answers2

0

There are no Sequence Points in that expression, so you can't work it out, it is undefined/compiler dependant.

Salgar
  • 7,687
  • 1
  • 25
  • 39
0

It is as defined by the C/C++ standards an undefined or implementation-defined behavior. The language standards do not specify the behavior, it allows the compiler implementation to choose (and is usually documented).

Also look at another StackOverflow question: Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…).


What GCC does in your example is the following:

int i = 5;
a = ++i + (++i + ++i);  // it first gets the value of i and increments it two times
a = ++i + (7 + 7);  // it then reads the new value of i, does the addition and save it as a constant in the stack
a = ++i + 14;  // it then gets the value of i and increments it
a = 8 + 14;  // it then reads the new value of i and add it to the constant
a = 22;
Community
  • 1
  • 1
Kyle_the_hacker
  • 1,394
  • 1
  • 11
  • 27
  • "Undefined" is very different from "implementation-defined". In this case, it's undefined. – molbdnilo Aug 05 '13 at 14:15
  • @molbdnilo: Since the compiler compiles and the program give a results **it is** defined. – Kyle_the_hacker Aug 05 '13 at 14:17
  • @Kyle_the_hacker: No. One of the consequences of being undefined is that the compiler can do anything, including compile it and give a result. In fact, for undefined behavior, it is almost always the case that it does this, because it is the simplest thing to do (no need to special case it) – Benjamin Lindley Aug 05 '13 at 14:19
  • It is also very unlikely that a compiler documents what it will do in such a case (and the behavior can be very different with different compiler settings like optimization levels). – Hulk Aug 05 '13 at 14:29