Why printf() in while() as a condition prints different output
while
takes a statement after the closing )
.
6.8.6 Iteration statements
iteration-statement:
while ( expression ) statement
....
In
while(printf("Hello"))
return 0;
that statement (which is basically while
's argument) is return 0;
(6.8.6)
In
while(printf("Hello"));
the statement is ;
(an empty (null)/expression statement (6.8.3)).
In
while(printf("Hello")){}
it's an empty compound statement ({}
, 6.8.2), which is semantically equivalent to ;
.
Your code snippets are examples of misleading whitespace—where the whitespace makes humans understand things differently from a compiler.
Less misleading renderings would be:
while(printf("Hello"))
return 0;
,
while(printf("Hello"))
; //or perhaps a {} instead of the null statement
and
while(printf("Hello"))
{}
printf
returns number of characters printed (which is 5). Any non zero number evaluates to true. So the loop is an infinite loop.
The rest depends on what happens withing the loop. In the second and third cases, the loops are empty (contain no statements) so they keep executing
In the first case, return 0
is executed within the loop. Return breaks the control flow out of the loop causing the loop (and in this case the program) to stop executing
In your first code snippet, the return 0;
statement is part of the while
loop's 'body'; in fact, it is the entirety of that body! So, on the first run through that loop, the program exits (because that what return 0;
does when executed in main
) and the loop is, thus, abruptly terminated.
In the second and third snippets, you have an empty body for the loop, but that does not prevent it from running, as the printf("Hello")
function call will return the number of characters that were output - which will be non-zero, and thus interpreted as "true".