[英]Why doesn't this code output anything?
Consider this "EXAM" question: 考虑这个“考试”问题:
int main()
{
int a=10,b=20;
char x=1,y=0;
if(a,b,x,y)
{
printf("EXAM");
}
}
Please let me know why this doesn't print anything at all. 请让我知道为什么这根本不打印任何东西。
Comma operator - evaluates 1st expression and returns the second one. 逗号运算符 - 计算第一个表达式并返回第二个表达式。 So
a,b,x,y
will return value stored in y, that is 0. 所以
a,b,x,y
将返回存储在y中的值,即0。
a,b,x,y
是y
(因为逗号运算符计算其右操作数的结果),y为0,这是假的。
The comma operator returns the last statement, which is y
. 逗号运算符返回最后一个语句,即
y
。 Since y
is zero, the if-statement evaluates to false, so the printf
is never executed. 由于
y
为零,因此if语句的计算结果为false,因此从不执行printf
。
Because expression a,b,x,y
evaluates to y
, which in turn evaluates to 0
, so corresponding block is never executed. 因为表达式
a,b,x,y
计算结果为y
,而y
又计算为0
,所以从不执行相应的块。 Comma operator executes every statement and returns value of last one. 逗号运算符执行每个语句并返回最后一个语句的值。 If you want logical conjunction, use
&&
operator: 如果您想要逻辑连接,请使用
&&
运算符:
if (a && b && x && y) { ... }
Others already mentioned that the comma operator returns the right-most value. 其他人已经提到过逗号运算符返回最右边的值。 If you want to get the value printed if ANY of these variables is true use the logical or:
如果要在任何这些变量为真时打印值,请使用逻辑或:
int main()
{
int a=10,b=20;
char x=1,y=0;
if(a || b || x || y)
{
printf("EXAM");
}
}
But then be aware of the fact that the comma evaluates all expressions whereas the or operator stops as soon as a value is true. 但是请注意以下事实:逗号评估所有表达式,而or运算符只要值为true就会停止。 So with
所以
int a = 1;
int b;
if(a || b = 1) { ... }
b has an undefined value whereas with b有一个未定义的值,而有
int a = 1;
int b;
if(a, b = 1) { ... }
b will be set to 1. b将设置为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.