Programming

Print Hello World in C without a semicolon

An empty if body lets a function call appear in a condition rather than in an expression statement.

A small ivory code card with abstract brackets and a single output line in a dark terminal

An empty if body lets a function call appear in a condition rather than in an expression statement. That makes this small C puzzle possible:

c
#include <stdio.h>

int main(void)
{
    if (printf("Hello, world!\n")) {
    }
}

There is no semicolon in that program. printf runs while the condition is evaluated. Its return value determines whether the empty body is entered, but the text has already been sent to standard output.

Why the return type matters#

Use int main(void) for this hosted C example. Neither void main nor a platform-specific console header is needed. In C99 and later, reaching the closing brace of main returns zero. This is a language rule, not a general license to omit return values from other functions.

Keep the trick out of ordinary code#

For normal work, a straightforward output statement is clearer. The point of the example is to distinguish a function call from the surrounding statement syntax, not to make punctuation disappear at any cost.

The C11 committee draft, section 5.1.2.2.3 describes main. The related comment-removal article looks at another case where surface characters can mislead a text-processing program.