Search code examples
c++c++17coutorder-of-executionsequence-points

C++ cout behavior / order of execution


I was looking at some example questions of CPPInstitute's CPA-21-01 exam, and am a bit confused about Question #11. It states the following:

What is the output of the following program?

#include <iostream>

using namespace std;

class A {
public:
    A() {
        a.a = a.b = 1;
    }
    struct { int a,b; } a;
    int b(void);
};

int A::b(void)
{
    int x=a.a;
    a.a=a.b;
    a.b=x;
    return x;
}

int main(void) {
    A a;
    a.a.a = 0;
    a.b();
    cout << a.b() << a.a.b << endl;

    return 0;
}

A. The program will cause a compilation error

B. 10

C. 01

D. 11

It can be boiled down a more minimal example:

int swap_and_return(int& a, int& b) {
    std::swap(a,b);
    return a;
}

int main() {

    int a = 0;
    int b = 1;

    cout << swap_and_return(a,b) << a << endl;

    return 0;
}

So far so good; The answer key says it's B.

Let's say you choose D.

According to this, the execution order is arbitrary:

15) In a function call, value computations and side effects of the initialization of every parameter are indeterminately sequenced with respect to value computations and side effects of any other parameter.

There has already been a similar question here

I think the cout line can be translated into cout.operator<<(a.b()).operator<<(a.a.b);, meaning there should be a sequence point and behavior should be deterministic?

In practice, the following results are obtained:

MS cl.exe, Debug: 10

MS cl.exe, Release: 11

GCC, C++11: 11

Clang: 11

Needless to say, I am a bit confused now, because they say it's answer B when it appears that indeed order of execution is arbitrary.

Could anyone please explain whether I am right about the execution order and what it should be then?

Thanks!


Solution

  • Before C++17, you're right, and the quiz does not allow for the right answer.

    Since then, the answer is deterministic.