-1

I wrote a program

#include<stdio.h>
int main()
{
      int x=3;
       if((x)==1,2,4,5,6)
               printf("number found in the list\n");
       else
               printf("Number not found \n");

      return 0;
}

I was expecting the output to be "Number not found " but it is "Number found in the list " why it is so

kapil
  • 625
  • 12
  • 20

2 Answers2

5

The == operator has higher precedence than ,, therefore the if-clause evaluates to

if (((x) == 1),2,4,5,6)

which is always true since the last "element" of the comma operator "counts" (6).

From the C11 standard:

The left operand of a comma operator is evaluated as a void expression [...]. Then the right operand is evaluated; the result has its type and value.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
2

You're expecting (x) == 1,2,4,5,6 to be evaluated as "x is equivalent to one of 1, 2, 4, 5, or 6", but that's not how the comma operator works. This is actually evaluated as (x)==1, then 2, then 4, then 5, and then finally 6. Since 6 is not 0, the condition evaluates to true and the first branch is taken.

You'll either need to write

if ( x == 1 || x == 2 || x == 4 || x == 5 || x == 6 )

or, you'll need to use a loop:

int list[] = {1,2,4,5,6};
size_t listSize = sizeof list / sizeof *list;
int found = 0;

for ( size_t i = 0; !found && i < listSize; i++ )
  found = (x == list[i]);

if ( found )
{
  printf( "Number found in list\n" );
}
...
John Bode
  • 119,563
  • 19
  • 122
  • 198