Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why printf inside if condition works in c?

if(printf("Hello world")){}

The output for above code is

Hello world

My friend told me that the function printf returns the length of characters which is non zero here, so the condition is true.

But I can't understand why it executes that printf statement. Shouldn't printf be executed only when it is inside { }?

like image 768
Jatin Avatar asked Mar 22 '26 00:03

Jatin


1 Answers

The expression within if(expression) is always evaluated, and in your case that's a call to printf.

The value of this expression is used to determine if the body (blank in your case) of the if is run.

like image 184
Bathsheba Avatar answered Mar 23 '26 14:03

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!