有人可以为我得到的输出清除这个概念吗?

Can someone clear this concept for the output I am getting?

采访中有人问过这个问题。以下代码段的输出是什么?

#include <iostream>
using namespace std;

int main() {
    cout << (3,2,1)-(1,2,3) << endl; // in C++ too this prints -2
    printf("%d\n",(3,2,1)-(1,2,3)); // prints -2
    printf("%d\n",("%d",3,2,1)-(1,2,3)); // prints -2
    return 0;
}

根据输出我猜测它的 (1-3) = -2。但是如何从 (3,2,1) 中选择值 1,类似地从 (1,2,3) 中选择值 3?我猜的对吗?

这里使用了 comma operator 和 属性。

详细说明,来自 C11,章节 §6.5.17,逗号运算符

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value

并且,来自 C++11,第 5.18 章,

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (Clause 5). Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field.

所以,如果像

这样的语句
  (3,2,1)-(1,2,3)

评价,

  • (3,2,1), 3和2被(作为void表达式求和)丢弃,1是值。
  • (1,2,3), 1 和 2 被(计算为 void 表达式和)丢弃,3 是值。

所以,语句减少到 1 - 3 等于 -2.

同样的方法,你也可以使用更多的元素。

(3,2,1)表示计算所有表达式,return最后。 所以,确实如此:

  • 3 - 没有
  • 2 - 没有
  • 1 - return 1

及其他:

  • 1 - 没有
  • 2 - 没有
  • 3 - return 3

所以你的

cout << (3,2,1)-(1,2,3) << endl;

表示:

cout << 1 - 3 << endl;

你必须考虑逗号运算符 (,)

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.

你的情况:

(3,2,1) //evaluates to 1
(1,2,3) //evaluates to 3

来源: http://www.cplusplus.com/doc/tutorial/operators/

逗号运算符总是 returns 最后一个值,即

  1. 你的第一个 cout 是 1-3=-2
  2. 接下来,在printf中又是1-3=-3
  3. 终于在最后printf,又是1-3=-2

逗号运算符总是解决所有左边的表达式(操作数)和 returns 最右边的操作数作为结果 rvalue