当我们 return 具有两个值的整数时,C 中的逗号运算符会做什么?

What does comma operator in C do when we return an integer with two values?

当我输入 , 而不是 . 时,我实际上返回了一个 float 值,但它没有给我任何错误。然后我尝试了 运行 下面的代码。

#include<stdio.h>
#include<conio.h>
int getValue();
int main()
{
    int a = getValue();
    printf("%d", a);
    return 0;
}

int getValue()
{
    return 2, 3;
}

现在输出为3,即返回第二个值。这件事发生在两年前,从那时起就在寻找合适的答案。

研究answers to this question我开始知道它returns求值后的第二个值,但它与第一​​个值有什么关系?

我研究了堆栈的逻辑(如何在内部推送和弹出值),但我认为这与它没有任何关系。

它是处理这两个值还是做其他事情?

逗号运算符将从左到右计算,return最右边的表达式或值。这相当于:

int getValue()
{
    (void)2;
    return 3;
}

引用 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.

现在,回答你的问题

what does it do with the first one?

我们可以说,第一个操作数(左手操作数)是求值,结果是丢弃

注意:我提到的是结果,而不是效果

澄清一下,在你的情况下,你不会注意到效果,但你可以注意到它的效果,如果左手和右手表达式与同一个变量相关。例如,让我们讨论一个简单的例子

return p=3, p+2;

我们可以将 return 语句分解为

  • 给变量 p 赋值 3 [, 的左侧运算符]
  • 执行p+2,即生成一个5的值。 [,]
  • 的右侧运算符
  • return5 作为第二个参数的值 [在子句之后:"the result (of , operator) has its (evaluation of right-operand) type and value."]

看到一个live demo.