int main(void)
{
int a=0, b=20;
char x=1, y=10;
if(a,b,x,y)
printf("bye");
return 0;
}
How does "if" condition in the above code work work? Would the value of "y" be only considered by "if"?
int main(void)
{
int a=0, b=20;
char x=1, y=10;
if(a,b,x,y)
printf("bye");
return 0;
}
How does "if" condition in the above code work work? Would the value of "y" be only considered by "if"?
Yes, the value of the comma operator is the right operand. Because none of the other operands have side effects, this boils down to if (y)
.
From Wikipedia:
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).
This in effect means that only the final operand is evaluated for truthfulness, the results of the previous operands are discarded.
In if(a,b,x,y)
only the truthfulness of y
is considered and therefore whatever y
has evaluated to will be considered as true/false.
In your case y
is equal to 10 which is considered true
in C, therefore the if
check will also evaluate to true
and the if
block will be entered.
You might want to consider this very popular question on StackOverflow for its uses (and misuses).
,
(comma) operator separates the expression.if the multiple values are enclosed in round bracket then the last value in round bracket gets assigned to variable.
e.g a=(x,y,z);
then a=z;
while if,
a=x,y,z;
then above expression gets evaluated to (a=x);
Please refer this.
As Joey said above this evaluates to nothing more than
if (y)
....
It is important to observe that if your code had read:
int main(void)
{
int a=0, b=20;
char x=1, y=10;
if(a++,b++,x++,y)
printf("%d, %d, %d, %d\n", a, b, (int)c, (int)y);
return 0;
}
The output would have been
1, 21, 2, 10
All the increments would have been executed but for the purposes of evaluating the condition
(a++,b++,x++,y)
the only one that matters is the last one, namely y