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;
}
Jabberwocky
  • 45,262
  • 17
  • 54
  • 100
wabavid
  • 11
  • 3
  • Have a look at https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do – aep Feb 17 '20 at 11:10

2 Answers2

4

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).

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
2

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.

Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303