1

One of my friends ask me about this code and I and he are unable to find out, what is happening in the if condition. Can you guys explain how this condition works?

int main()
{
   int i;

   if (i = (1, 2, 0))
       printf("Mehrose");
   else
       printf("Hello ");

   printf("%d\n", i);

   return 0;
}

The output for this code is Hello 0

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Rose
  • 59
  • 7

2 Answers2

3

First, formatting as the compiler sees the code we get:

int main(void)
{
   int i;
   if(i=(1,2,0))
      printf("Mehrose");
   else 
      printf("Hello");
   printf("%d\n",i);
   return 0;
}

The if statement can be broken down:

  1. Comma operator , is evaluated first, left-hand side of the operator is discarded. This repeats for each operator:

    if(i=(1,2,0))

    if(i=(2,0))

    if(i=0)

  2. The assignment operator = assigns a value of 0 to i, and returns the right-hand side of the expression:

    if(0)

  3. Recall that 0 is evaluated as false (is "falsy") and 1 is evaluated as true (is "truthy"). Thus the first condition fails and the second block is executed. "Hello" is printed to the standard output stream, followed by "0".

2

In the expression,

i=(1,2,0)

you're using the comma operator, which evaluates all its operands and yields the result of its rightmost operand - which is 0 here. So 0 is assigned to i.

So it's equivalent to if (i = 0), which assigns 0 to i and yields the value of i which is false and thus it prints the string in the else branch.

P.P
  • 117,907
  • 20
  • 175
  • 238