-2

I want to know on what criterias,gcc compiler decides to optimize the values of variables.? Here is sample

int a=2;
printf("%d %d\n",a++,++a);

It gives output 3 4

Why does gcc optimizes and gives latest value of ain pre-increment and not in post increment?On which basis it takes decision?

Arya
  • 371
  • 2
  • 17

2 Answers2

3

It's undefined behavior. There is no specified order in which arguments are evaluated.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 3
    It is undefined behavior because a is changed twice in the same expression with no sequence point in between. The order of evaluation of function arguments is not UB, it is _unspecified behavior_. These are two separate issues. – Lundin Oct 01 '13 at 11:39
3

The code has two problems.

  • You change the value of a twice in the same expression, with no so-called "sequence point" between them. This is undefined behavior and anything can happen. See the FAQ for more information.

  • You have side effects in the parameters passed to a function, the side effect being a ++ increment. The order of evaluation of function parameters is unspecified behavior, meaning that the compiler has implemented it in some way, but we can't know how. It may be different from function to function, and certainly different from compiler to compiler.

One should never write code that relies on undefined or unspecified behavior. Even more info in the FAQ.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396