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.
The result of a,b,x,y
is y
(because the comma operator evaluates to the result of its right operand) and y is 0, which is false.
The comma operator returns the last statement, which is y
. Since y
is zero, the if-statement evaluates to false, so the printf
is never executed.
Because expression a,b,x,y
evaluates to y
, which in turn evaluates to 0
, so corresponding block is never executed. 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. So with
int a = 1;
int b;
if(a || b = 1) { ... }
b has an undefined value whereas with
int a = 1;
int b;
if(a, b = 1) { ... }
b will be set to 1.
精彩评论