Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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 
like image 733
Ani Avatar asked Jul 09 '13 05:07

Ani


People also ask

What does if 0 mean in C?

In C, zero is false. Non zero is true. It is a kind of clever way to comment.

Can we assign value in if condition?

Yes, you can assign the value of variable inside if.

Can we assign value in if condition in C?

Can we put assignment operator in if condition? Yes you can put assignment operator (=) inside if conditional statement(C/C++) and its boolean type will be always evaluated to true since it will generate side effect to variables inside in it.

What is if condition in C?

Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to specify many alternative blocks of code to be executed.


2 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.

like image 74
trojanfoe Avatar answered Oct 18 '22 03:10

trojanfoe


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.

like image 28
Jim Balter Avatar answered Oct 18 '22 04:10

Jim Balter