What is the difference betweenif(a == (1,2))
and if(a == 1,2)
?
#include<stdio.h>
int main()
{
int a = 2;
if(a == (1,2))
printf("Hello");
if(a == 1,2)
printf("World");
return 0;
}
What is the difference betweenif(a == (1,2))
and if(a == 1,2)
?
#include<stdio.h>
int main()
{
int a = 2;
if(a == (1,2))
printf("Hello");
if(a == 1,2)
printf("World");
return 0;
}
a == 1,2
is equivalent to (a == 1),2
due to operator precedence
And because of how the comma operator works, (a == 1),2
will result in 2
. And a == (1,2)
will be the same as a == 2
.
So in effect your two conditions are like
if (a == 2)
printf("Hello");
if(2)
printf("World");
The first condition will be true only if a
is equal to 2
. The second condition will always be true (only zero is false).
In the both conditions of the if statements there is used the comma operator
The second condition is equivalently can be rewritten like
if( ( a == 1 ), 2)
The value of the comma operator is the value of the second operand. So the condition in the second if statement will always evaluate to true because 2 is not equal to 0.
The condition in the first if statement can be rewritten like
if(a == 2)
because the first expression (the integer constant 1) of the comma operator has no effect.
So the condition of the if statement evaluates to true only when a is equal to 2.