Search code examples
cpre-increment

Undefined behavior while using increment operator


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 .


Solution

  • 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.