Search code examples
c++language-lawyerorder-of-executionsequence-pointscompiler-specific

Different results obtained when using MSVC compiler and GCC compiler


I have this simple little code:

#include <iostream>

int Add (int x, int y) {
    std::cout << "In Add(), received " <<x<< " and " <<y<< "\n";
    return (x+y);
}

int main () {
    std::cout << "In main ()\n";
    std::cout << "\nCalling Add ()\n";
    std::cout << "value: " << Add (3,4);
    std::cout << "\nback to main ().\n";
    std::cout << "\nout..\n\n";
    return 0;
}

If I compile this with the MSVC compiler, the result is:

In main ()

Calling Add ()
In Add(), received 3 and 4
value: 7
back to main ().

out..

But in GCC, the result is:

In main ()

Calling Add ()
value: In Add(), received 3 and 4
7
back to main ().

out..

Why is the output not the same? I was also wondering if there is a way for both compilers to have the same output.


Solution

  • Before c++17, operator << is not a sequencing point, therefore std::cout << "value: " << Add (3,4); can be evaluated in any order.

    C++17 guarantees evaluation from left to right which is the wrong behaviour in your case.

    My guess is the particular versions of the compilers you are using have different default C++ version and MSVC evaluates the expression from right to left.

    You should split the expression into multiple statements. In general, my advise is to split computation from reporting, i.e. do not have any computation in logging or otherwise conditional (like assert) parts.