What happens when a variable is assigned to zero in an `if` condition?

It would be helpful if anybody can explain this.

int main()
{ int a=0; if(a=0) printf("a is zero\t"); else printf("a is not zero\t"); printf("Value of a is %d\n",a); return 0;
}

output of this is

a is not zero Value of a is 0 
13

4 Answers

The result of the assignment is the value of the expression.

Therefore:

if (a = 0)

is the same as:

if (0)

which is the same as:

if (false)

which will force the else path.

0
if(a=0) printf("a is zero\t"); else printf("a is not zero\t");

These messages are precisely backwards. The statement after the if is executed if the condition isn't 0, and the statement after the else is executed if the condition is 0, so this should be

if(a=0) printf("a is not zero\t"); else printf("a is zero\t");

Or, equivalently but more clearly,

a = 0;
if(a) printf("a is not zero\t"); else printf("a is zero\t");

Which, together with

printf("Value of a is %d\n",a);

would print

a is zero Value of a is 0 

as expected.

1

If () function accepts true or false value as an argument.

So whatever you put inside the bracket has no significance to if() function but of the fact what value it has.

'0' in any case is considered as false value, so when you pass 0 as an argument like:

if(0)
{ ---statments---
}

The statement part of will not get executed, and the system will directly jump to else part.

In the case you mentioned you assigned 0 to your variable and passed it as an argument to if(). Note that if() only accepts 0 or non 0 value. So, it doesn't matter what assignment you made. if() will recieve the value of your variable 'a' as an argument and act accordingly.

In this case, since the value of a is 0, the if part will not get executed and the system will jump to else.

if(a=0) is assignement of 0 in variable a. if you want to compare a against zero you need to write like belowif(a==0)

your condition is simple assignment which is making a as zero so condition getting false and you are getting prints from else part.

2

You Might Also Like