Moithil Biswas Moithil Biswas - 3 months ago 10
C Question

Why else block is executed if num1, num2, and 0 at the end is assigned to if block?

In this code

#include <stdio.h>
int main(){
int i;

if(i= 50,40)
printf(" if blk i %d\n",i);
else
printf(" else part" );



return 0;
}


the output comes as


if blk i 50


but when a zero is added to the assignment part in if statement, it goes to the else part. Why is this 0 making it go to else part?

the code below:

#include <stdio.h>
int main(){
int i;

if(i= 50,40,0)
printf(" if blk i %d\n",i);
else
printf(" else blk i %d\n", i);

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

return 0;
}

Answer

this statement:

if(i= 50,40)

is actually a:

if(40)

comma operator causes first i to be assigned to 50, then as a condition a last element is used which is 40

but when a zero is added to the assignment part in if statement, it goes to the else part.

becasue then as a condition a last element is used which is 0. 0 causes if to fail, and execute else block.