Reputation: 33
I have learned that the if
condition can take one of 2 values, 0 or 1, as input.
Now I've stumbled upon the following code:
#include <stdio.h>
int main(void)
{
if (printf("Hello World")) { }
}
In the condition we have a function does not give 0 or 1 whereas gives a set of characters as an output.
At first I expected an error, but I didn't get one and the code runs OK.
Can someone please explain me the reason for this behavior
Thanks
Upvotes: 2
Views: 104
Reputation: 48020
I have learnt that "if" condition can only take 0 or 1 as input.
Absolutely not true. A condition can take almost anything, which is interpreted as false if it's equal to 0, or true if it's not equal to 0.
I was expecting an error when I first saw it but because of printf but it isn't giving.
Right. Why would you expect an error? printf
returns an int
value, so it's perfectly fine. (And in this case, it doesn't even matter whether printf
returns zero or nonzero, because there's nothing that happens in the body of the if
statement.)
Upvotes: 6