This program compiles (C with diab):
It compiles for the same reason that
1 + 2 + 3 + 4; would compile: because an expression, followed by a semicolon, is a valid statement.
Turning expressions into statements with a semicolon is needed for a lot of parts of C to work. For example:
is a function call, which has a value, but can be useful as a statement in its own right.
Even something like
x = y;
(that is, an assignment) is actually an expression. This one in particular is quite useful in statement position.
The relevant parts of the C grammar are:
statement : labeled_statement | compound_statement | expression_statement | selection_statement | iteration_statement | jump_statement ;
that is, a
statement can be one of many things, including an
expression_statement : ';' | expression ';' ;
that is, an
expression_statement is either a semicolon or an
expression, followed by a semicolon.
What this program compiles to is implementation-dependent. A compiler is free to compile the string into the data segment of the program, or it is free to simply ignore it. On my machine, GCC does not even put the string in the compiled executable at all, even with no optimization level.
Compilers are also not required to warn about this construct, but GCC does, when given the flag
-Wunused-value. This warning can be helpful sometimes, because this particular construction is not useful at all.
test.c: In function ‘main’: test.c:2:5: warning: statement with no effect [-Wunused-value] ("----"); ^