P.S. P.S. - 1 year ago 63
C Question

Why does a string in parenthesis compile and what does it compile to?

This program compiles (C with diab):

int main()


  • Why is it not considered a compiler error ? (Is it because it supports some other feature that needs this syntax)?

  • What does it compile to?

Answer Source

It compiles for the same reason that 1;, "----";, or 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:

    : 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; and

    : ';'
    | 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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download