此语句在 C 或 C++ 中如何工作 `int k = (a++, ++a);`

How this statement works `int k = (a++, ++a);` in c or c++

我无法理解下面代码的输出是“-3”吗?

#include <stdio.h>
void main()
{
    int a = -5;
    int k = (a++, ++a);
    printf("%d\n", k);
}

c 或 c++ 中 int k = (a++, ++a); 语句背后的概念是什么?

之所以有效,是因为 , 运算符创建了 sequence point

§5.19.1(逗号运算符)

The comma operator groups left-to-right. 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. If the value of the right operand is a temporary (12.2), the result is that temporary.

因此:

  1. a初始化为-5
  2. 然后a++执行,修改a-4.
  3. 然后++a执行,修改a-3,returns-3修改为k

这不是未定义的行为

在您的代码中,

 int k = (a++, ++a);

正在使用"comma operator"。在 a 初始化为 -5 之后,基本上,

  • 执行a++,丢弃结果。 post-++a 的副作用现在是 -4
  • 遇到,,序列点
  • 执行++a、return结果a 现在是 -3(pre-++),它被分配给 k.

参考:来自 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 和 C++ 中都有很好的定义。

逗号分隔的表达式从左到右计算。

整个表达式的值将是第二个表达式的值。

所以,要分解(a++, ++a),首先计算a++(然后a是-4)结果(-5)丢弃,然后计算 ++a。该值 (-3) 分配给 k.

这里使用了一个以逗号运算符作为初始值的表达式

int k = (a++, ++a);

根据 C 标准(同样适用于 C++)(6.5.17 逗号运算符):

2 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

最初变量a被初始化为-5

int a = -5;

因此,在对逗号运算符的第一个表达式求值后,由于“在其求值与右操作数[=27=之间存在一个序列点]" a 将等于 -4 (a++)。带有逗号运算符的整个表达式的结果将是计算正确表达式 ++a 后的值。它的值为-3

因此变量 k 将被初始化为 -3。相同的值会有变量 a.