Ani
Ani

Reputation: 197

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 

Upvotes: 10

Views: 99261

Answers (4)

Jim Balter
Jim Balter

Reputation: 16406

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.

Upvotes: 8

Chetan Bhasin
Chetan Bhasin

Reputation: 3571

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.

Upvotes: 1

Dayal rai
Dayal rai

Reputation: 6606

if(a=0) is assignement of 0 in variable a. if you want to compare a against zero you need to write like below if(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.

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

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.

Upvotes: 44

Related Questions