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
In C, zero is false. Non zero is true. It is a kind of clever way to comment.
Yes, you can assign the value of variable inside if.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With