C++ compiler commands ordering is not consistent

Viewed 108

I trying to run a simple c++ program, but I'm not sure why different compilers provide different output

#include <iostream>

struct A
{
    A() { std::cout << "Object A created" << std::endl; }

    friend std::ostream& operator<<(std::ostream& os, const A& a)
    {
        os << a.str << "\n";
        return os;
    }

    static bool printMe()
    {
        std::cout << "static bool printMe() of object A" << std::endl;
        return true;
    }
    std::string str{"This is object A"};
};


int main()
{
    std::cout << A() << (A::printMe() ? "TRUE" : "FALSE") << std::endl;
}

OUTPUT1: Some compilers provide the following output:

Object A created
This is object A
static bool printMe() of object A
TRUE

For example: https://www.programiz.com/cpp-programming/online-compiler/

OUTPUT2: Other compilers provide the other output:

static bool printMe() of object A
Object A created
This is object A
TRUE

For example: http://cpp.sh/

I cannot understand why some compilers execute the static function before creating object A I would expect the order will be kept and Object A will be created bfore static function will be called as in OUTPUT2.

1 Answers

Before C++17, the order of evaluating sub-expressions in an expression is mostly unspecified, the compiler is free to order them as it sees fit. In C++17, the order is more strictly defined, in particular:

In a shift operator expression E1<<E2 and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2 [cppreference]

So if you add -std=c++17, you should only see OUTPUT1.

?'s order has always been defined, so that's safe.

Related