如果条件为逗号运算符 [英] comma operator in if condition
问题描述
int a = 1, b = 0;
if(a, b)
printf("success\n");
else
printf("fail\n");
if(b, a)
printf("success\n");
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)
首先计算并舍弃,然后计算
b
在第二个如果
:
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.
这篇关于如果条件为逗号运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!