c++g++clangintel

Compiler differences in g++ 4.7.2 and Intel 13.0.1 vs clang++ 3.2 and g++ 4.8


According to the official C++ standard, could someone explain why there are differences in the output of the following simple code when run with different compilers?

In other words, does the standard leave this open as to what will happen first, the a++ or the b assignment?

This is not related to function parameters, it's the same piece of code run at different compilers. Here is the sample code:

#include <iostream>
using namespace std;

int main() {
    int a = 10, b;

    a = b = a+++a;
    cout << "a = " << a << ", b = " << b;

return 0;
}

Link of the code is here.

With g++ 4.7.2 and Intel C++ 13.0.1 you get:

stdout:
a = 21, b = 20

while with g++ 4.8.0 and Clang++ 3.2 you get:

stdout:
a = 21, b = 21

Which one is the right one? Thanks.


Solution

  • All of the compilers are right.

    In the line

    a = b = a+++a;
    

    you invoke Undefined Behaviour, because a gets modified twice without an intervening sequence point. If you do that, the C++ standard gives the compilers licence to do whatever they like.