C中的逗号和赋值运算符

时间:2012-12-13 15:35:15

标签: c c99 comma-operator

我有以下内容:

int a = 1, b = 2, c = 3, d = 4;
a = b, c = d;
printf("%d, %d, %d, %d", a, b, c, d);

输出结果为:

2, 2, 4, 4

逗号运算符如何与赋值运算符一起使用?据我所知,它将评估并返回第二个表达式,如果我们有,

(exp1, exp2)

那么,为什么会评估a = b

6 个答案:

答案 0 :(得分:5)

评估第一个操作数并丢弃结果。然后计算第二个操作数,结果作为表达式的整体结果返回。

标准说:

  

逗号运算符的左操作数被评估为void   表达;它的评估与之间存在一个序列点   正确的操作数。然后评估右操作数;结果   有它的类型和价值。

答案 1 :(得分:4)

逗号运算符的优先级低于赋值。将评估逗号运算符中的所有表达式,但仅将最后一个用作结果值。因此,两个任务都会执行。您案例中逗号运算符的结果将是c = d的结果。不使用此结果。

答案 2 :(得分:1)

逗号运算符计算其两个操作数(左边的第一个)并返回右操作数的值。这不是特定于操作数的分配。

答案 3 :(得分:1)

它的工作方式与将它们编写为单个语句的方式相同:

int a = 1;
int b = 2;
int c = 3;
int d = 4;

a = b;
c = d;

有关详细信息,请参阅Comma Operator

来自维基百科:

int a=1, b=2, c=3, i;   // comma acts as separator in this line, not as an operator
i = (a, b);             // stores b into i                                                              ... a=1, b=2, c=3, i=2
i = a, b;               // stores a into i. Equivalent to (i = a), b;                                   ... a=1, b=2, c=3, i=1
i = (a += 2, a + b);    // increases a by 2, then stores a+b = 3+2 into i                               ... a=3, b=2, c=3, i=5
i = a += 2, a + b;      // increases a by 2, then stores a into i. Equivalent to  (i = a += 2), a + b;  ... a=3, b=2, c=3, i=3
i = a, b, c;            // stores a into i                                                              ... a=5, b=2, c=3, i=5
i = (a, b, c);          // stores c into i  

答案 4 :(得分:0)

From what I have known it would evaluate and return the second expression

这不是一个完全正确的陈述。是的,第二个被评估并返回,但你暗示第一个被忽略。

逗号运算符的工作方式是计算所有表达式并返回 last 。例如:

int a, b, c, d = 0;
if(a = 1, b = 2, c = 3, d == 1)
    printf("No it isn't!\n")
else
    printf("a: %d, b: %d, c: %d, d: %d\n", a, b, c, d);

给你:

a = 1, b = 2, c = 3, d = 0

因为评估了所有表达式,但只返回d==1来决定条件。

...此运算符的更好用途可能是for循环:

for(int i = 0; i < x; counter--, i++) // we can keep track of two different counters
                                      // this way going in different directions.

答案 5 :(得分:0)

此代码与此相同:

int a = 1;
int b = 2;
int c = 3;
int d = 4;
a = b;
c = d;

评估逗号左侧的第一个表达式,然后评估右侧的表达式。最右边表达式的结果存储在= sign。

左侧的变量中
相关问题