当我输入 ,
而不是 .
时,我实际上返回了一个 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我开始知道它在求值后返回第二个值,但它对第一个值有什么作用?
我研究了堆栈的逻辑(如何在内部推送和弹出值),但我认为这与它没有任何关系。
它是处理这两个值还是做其他事情?
引用 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?
我们可以说,第一个操作数(左手操作数)被求值,结果被丢弃。
注意:我提到的是结果,而不是效果。
澄清一下,在您的情况下,您不会注意到该效果,但您可以注意到如果左右 watch 达式都与同一个变量。例如,让我们讨论一个简单的例子
return p=3, p+2;
我们可以像这样分解return
语句
- 将值
3
赋给变量 p
[,
的左侧运算符]
- 执行
p+2
,生成值5
。 [,
的右侧运算符]
返回
值 5
作为第二个参数的值 [在子句之后:“结果(,
运算符)有它的(右操作数的评估)类型和值。”]
查看 live demo .