Jatin
Jatin

Reputation: 81

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 { }?

Upvotes: 3

Views: 7119

Answers (4)

Luis Colorado
Luis Colorado

Reputation: 12698

To evaluate the return value from printf() function, the program must execute it. This is why the printing happens. It is executed just to evaluate the return value. This is often called side effect or collateral effect. C allows any expression in the test part of an if statement except one that returns void (another way of saying no return function or procedure), union or struct

Upvotes: 0

DWAD WADW
DWAD WADW

Reputation: 11

printf is returning 11 , cause the count is 11.

Upvotes: -1

user11830230
user11830230

Reputation:

printf() function return the number of characters that are printed. If there is some error while printing, it will return a negative value. Look at this snippet from GNU C library.

    int
__printf (const char *format, ...)
{
  va_list arg;
  int done;
  va_start (arg, format);
  done = __vfprintf_internal (stdout, format, arg, 0);
  va_end (arg);
  return done;
}

Here printf returns 11 since, the count of characters it printed is 11.

if(11) is true => It will be true as 11 is a positive integer, so the body of if() will be executed.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234795

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.

Upvotes: 7

Related Questions