Search code examples
ccomma-operator

What is the difference between if(a == (1,2)) and if(a == 1,2)?


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;
}

Solution

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