Search code examples
c++comma-operator

What is the output of "cout << (a, b)" and why?


It is possible to combine boolean expressions with a comma separator. I have seen it in a code and i am not sure what this resolves to. I wrote some sample code.

int BoolStatement(void)
{
    using std::cout;
    using std::endl;

    cout << "(0, 0) => " << (0, 0) << endl;
    cout << "(0, 1) => " << (0, 1) << endl;
    cout << "(1, 0) => " << (1, 0) << endl;
    cout << "(1, 1) => " << (1, 1) << endl;
    cout << "(0, 0) => " << (0, 0) << endl;
    cout << "(0, 3) => " << (0, 3) << endl;
    cout << "(5, 0) => " << (5, 0) << endl;
    cout << "(7, 1) => " << (7, 1) << endl;

    cout << endl;
    return 0;
}

The output of this is:

(0, 0) => 0
(0, 1) => 1
(1, 0) => 0
(1, 1) => 1
(0, 0) => 0
(0, 3) => 3
(5, 0) => 0
(7, 1) => 1

I am not sure if that is only true for my system and if this call is actually the same as a boolean combination of statements.

What is the output, is it the same on all systems? Why is that statement possible and is there documentation on it?


Solution

  • What is the output, is it the same on all systems?

    The output is as you describe: the second of the two values. It's well defined.

    Why is that statement possible?

    Because the comma operator allows you to evaluate more than one thing in a single expression.

    is there documentation on it?

    It's documented in the C++ standard, [expr.comma]. In C++11, that's 5.18.

    To summarise, the comma operator:

    • evaluates the expression before the comma;
    • discards that value;
    • evaluates the expression after the comma;
    • yields that value as the overall expression value.

    You can see that from your output: in each case, the output is the value after the comma.

    It's completely pointless in this case; but is useful if the first expression has side-effects which you want to sequence before the second, in a situation that only allows a single expression. For example:

    for (int i = 0, j = n; i < j; ++i, --j)
    

    The operator allows the final expression to do two things, even though you can only put one expression there.