鱼C论坛

 找回密码
 立即注册
查看: 2128|回复: 2

[已解决]求值的问题

[复制链接]
发表于 2022-7-31 10:32:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
为什么这程序运行后的结果是1,而不是7呢?
#include <stdio.h>
int main(void)
{
  int a = 1;
  printf("%d\n", (a + 5, a++));
  return 0;
}
最佳答案
2022-7-31 12:26:27
参考标准
6.3.2.2 void
1 The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)

6.5.17 Comma operator
...
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 在左侧,没有副作用且求值结果被丢弃;随后完成 a++ 的求值,整个表达式的值为 1 。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-7-31 10:34:19 | 显示全部楼层
是因为没有赋值运算符吗,可是如果是printf函数的话不是只用跟表达式吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-31 12:26:27 | 显示全部楼层    本楼为最佳答案   
参考标准
6.3.2.2 void
1 The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)

6.5.17 Comma operator
...
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 在左侧,没有副作用且求值结果被丢弃;随后完成 a++ 的求值,整个表达式的值为 1 。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-12-28 22:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表