0

I am new to C, i have an Increment operator program in C

#include<stdio.h>
main(){
  int a, b;
  a = 2;
  b = a + ++a + ++a;
  printf("%d", b);
  getchar();
}

The output is 10, can someone explain me how the output will be 10 .

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
useCase
  • 1,265
  • 6
  • 22
  • 41

2 Answers2

6
a + ++a + ++a;

Behaviour for this is undefined. The compiler might generated code that evaluated this as 2 + 4 + 4 or 3 + 3 + 4, but any combination/ordering of incrementing and accessing is a "valid" result.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • couldn't it also be `4 + 4 + 4` (increments first?) – KevinDTimm Jul 21 '11 at 16:51
  • 1
    Not only that, but since the behavior is undefined, printing `42` or `Bad diff! No cookie!` is a valid behavior (just extremely unlikely in practice). So is making the computer burst into flames, or as the classical formulation goes, making demons fly through your nose. – Gilles 'SO- stop being evil' Jul 21 '11 at 16:51
  • sure, any ordering is fine. I just wrote examples that add up to 10. – Karoly Horvath Jul 21 '11 at 16:52
  • @Giles the behaviour is *not* undefined, the *order* of the behaviour is undefined. Printing `42` is not allowed. (You were right, however, to correct my use of the term "associative".) – spraff Jul 21 '11 at 16:55
  • @Gilles: I'm waiting for like 10 years to a compiler that does those things. It looks like I have to write it myself. – Karoly Horvath Jul 21 '11 at 16:55
  • why the Behaviour for this is undefined? – useCase Jul 21 '11 at 17:15
3

This is undefined, the ++i can happen in any order.

Function call arguments are also ambigiously evaluated, e.g. foo(++i,++i).

Not all operator chains are undefined, a||b||c is guaranteed to be left-to-right, for example.

The guarantees are made in places known as sequence points although this terminology is being deprecated and clarified in C++0x.

What's odd in your example is that neigher 2+3+4 nor 4+4+3 happened, so the compiler evaluated the left side first in one step and the right side first in the other. This was probably an optimisation to flatten the depencency graph.

spraff
  • 32,570
  • 22
  • 121
  • 229
  • It's not just that the `++i` can happen in any order: there's no sequence point around operators (except `&&`, `||`, `?:` and `,`), nor is there one around the `,` that separates function arguments. See e.g. [N1256](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) §C and §5.1.2.3. If an object is both written and read with no intervening sequence point, the behavior is undefined (§6.5.16.3). – Gilles 'SO- stop being evil' Jul 21 '11 at 17:07