"cout << (a, b)" 的输出是什么,为什么?

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

可以将布尔表达式与逗号分隔符结合起来。我在代码中看到过它,但我不确定它的解析结果。我写了一些示例代码。

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;
}

这个输出是:

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

我不确定这是否仅适用于我的系统以及此调用实际上是否与语句的布尔组合相同。

输出是什么,在所有系统上都一样吗? 为什么该声明是可能的,是否有相关文档?

逗号运算符 returns 右侧。

Wikipedia:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

这是因为它 returns 您的表达式序列的最后一个值,在您的示例中:

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

一个看起来像这样的表达式

(a, b)

是一个comma expression,它的值是它的结果是它最右边的操作数,即

(a, b, ..., z)

将产生 z 的值。

请注意,链中的所有表达式都会被计算,包括具有副作用 的表达式。此外,逗号充当 序列点 ,这意味着在评估下一个操作数之前应用副作用。

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

输出如您所描述:两个值中的第二个。定义的很清楚。

Why is that statement possible?

因为 逗号运算符 允许您在单个表达式中评估多个事物。

is there documentation on it?

它记录在 C++ 标准中,[expr.comma]。在 C++11 中,那是 5.18.

总而言之,逗号运算符:

  • 计算逗号前的表达式;
  • 丢弃该值;
  • 计算逗号后的表达式;
  • 将该值作为整体表达式值。

您可以从输出中看到:在每种情况下,输出都是逗号后的值。

在这种情况下完全没有意义;但是如果第一个表达式有副作用,你想在第二个表达式之前排序,在只允许单个表达式的情况下,这很有用。例如:

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

运算符允许最终表达式做两件事,即使您只能在其中放置一个表达式。

在 C++ 中,逗号运算符为编译器提供计算顺序。通常编译器可以按照自己喜欢的方式自由地计算任何表达式。但是逗号运算符在右手操作数和 returns 右手操作数的值之前评估其左手操作数。

在由逗号运算符链接的操作数链中,返回值是最右边的操作数。