c 中的逗号运算符

Comma operator in c

#include<stdio.h> 
int main(void) {
   int a;
   a = (1, 2), 3; 
   printf("%d", a);
   return 0;
}

输出:2
谁能解释一下输出是 2 吗?

Can any one explain how output is 2?

因为赋值运算符=)的优先级高于逗号运算符,).

因此,声明:

a = (1, 2), 3;

相当于:

(a = (1, 2)), 3;

表达式 (1, 2) 的计算结果为 2.

Can any one explain how output is 2?

在声明中

a = (1, 2), 3;   

,用的是一个comma operator。 由于 = 运算符的运算符优先级高于 , 运算符,表达式操作数 (1, 2) 将绑定到 = 作为

(a = (1, 2)), 3;  

如果是逗号运算符,逗号运算符的左操作数被计算为 void 表达式,然后右操作数被计算,结果具有右操作数的值和类型

这里有两个逗号运算符。对于表达式 (1, 2) 中的第一个逗号运算符,1 将被计算为 void 表达式,然后 2 将被计算并分配给 a.
现在 a 的副作用已经发生,因此第二个逗号运算符 3 的右操作数将被计算,表达式 (a = (1, 2)), 3 的值将是 3.

结果:

a = x, y     =>     x

a = (i, j)   =>     j

因此,如果我们有:

x = (1 , 2)

a = (1 , 2) , 3     =>     2

如前所述here:

The comma operator separates expressions (which have value) in a way analogous to how the semicolon terminates statements, and sequences of expressions are enclosed in parentheses analogously to how sequences of statements are enclosed in braces: (a, b, c) is a sequence of expressions, separated by commas, which evaluates to the last expression c while {a; b; c;} is a sequence of statements, and does not evaluate to any value. A comma can only occur between two expressions – commas separate expressions – unlike the semicolon, which occurs at the end of a (non-block) statement – semicolons terminate statements.

The comma operator has the lowest precedence of any C operator, and acts as a sequence point. In a combination of commas and semicolons, semicolons have lower precedence than commas, as semicolons separate statements but commas occur within statements, which accords with their use as ordinary punctuation: a, b; c, d is grouped as (a, b); (c, d) because these are two separate statements.

我希望这能回答你的问题。