-1

Today I found something, that made me very anxious about my C++ or basic programming skills. The problem is C++ expression evaluation with post/pre incrementation.

Let's check this, let me say that, trivial example of code:

int a = 5;
int d = a++ + a;

As far as I expected, left and right operands of '=' sign would be calucalted independently, and the final result is (a++) 5 + (a) 5, where post-incremented 'a' has value of 6after 'd' is computed.

But, here's what I got under two popular C compilers:

MinGW: d == 11;
MSVC:  d == 10;

Same situation is with:

int a = 5;
int d = a-- + a;

where compilers gave:

MinGW: d == 9;     // 5 + 4  , a=4 after 'a--', before '+a'?
MSVC:  d == 10;    // 5 + 5  , a=4 after 'a-- + a'?

MSVC out is exact as what I expected. Question is what is really happening here? Which compiler is closer to the behaviour defined as standard?

Invader
  • 105
  • 1
  • 12
  • 3
    This `a-- + a` is undefined behavior, there are a lot of questions about it on stack overflow, just search about **sequence point**. – Iharob Al Asimi Jan 25 '15 at 01:57

2 Answers2

2

Funny that you should ask about the "behaviour defined as standard"; in fact, both compilers adhere perfectly to the standard, since your programs invoke undefined behaviour.

In a nutshell, the operands to + (and most other binary operators) are unsequenced relative to each other: they can be evaluated in either order, and depending on a particular order (via side effects) invokes undefined behaviour.

With undefined behaviour, of course, a conforming compiler can choose to do anything, legally.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

The order of execution for the expression a++ + a is unspecified by the C++ standard, so each compiler is free to evaluate the expression however it wants. Since both are compilers are correct, you need to rewrite your expression into two separate statements to get the particular behavior that you want.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Hawkmooon
  • 508
  • 3
  • 9