comma operator in if condition(if 条件中的逗号运算符)
问题描述
int a = 1, b = 0;
if(a, b)
printf("success
");
else
printf("fail
");
if(b, a)
printf("success
");
else
printf("fail");
这是一个 cpp 文件,我在 Visual Studio 2010 中得到的输出为
This is a cpp file and I got the output in Visual Studio 2010 as
fail
success
为什么会有这种行为?你能解释一下吗?
Why this behavior? Could you please explain?
推荐答案
http://en.wikipedia.org/wiki/Comma_operator:
在 C 和 C++ 编程语言中,逗号运算符(由标记 , 表示)是一个二元运算符,用于评估其第一个操作数并丢弃结果,然后计算第二个操作数操作数并返回此值(和类型).
In the C and C++ programming languages, the comma operator (represented by the token
,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
在你的第一个 if 中:
if (a, b)
a 首先被评估并被丢弃,b 被第二次评估并返回为 0.所以这个条件是假的.
a is evaluated first and discarded, b is evaluated second and returned as 0. So this condition is false.
在你的第二个if中:
if (b, a)
b 首先评估并丢弃,a 第二次评估并返回 1.所以这个条件为真.
b is evaluated first and discarded, a is evaluated second and returned as 1. So this condition is true.
如果有两个以上的操作数,则返回最后一个表达式.
If there are more than two operands, the last expression will be returned.
如果您希望这两个条件都成立,您应该使用 &&运算符:
If you want both conditions to be true, you should use the && operator:
if (a && b)
这篇关于if 条件中的逗号运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:if 条件中的逗号运算符
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
