Search code examples
ccompiler-constructionlalr

Why is a multiplication without an LHS valid in C?


Why is this piece of C code valid?

int main() {
    int x = 0, y = 0;

    x * y; // See this?!
}

The most ubiquitous examples that explain the need for back-tracking in parser often shows this. And then goes on to say that depending on what x is, the meaning of * will change. For some time, I believed it was just a way of explaining until I compiled it and found to my surprise, it compiles and works!

Why is a multiplication without an LHS valid in C and what is it used for?

Edit This confusion is because, the same piece of code won't compile in Java. It seems Java compiler tries to prevent operations without LHS.

enter image description here


Solution

  • This is referred to as an expression statement.

    From section 6.8.3 of the C standard:

    1
    expression-statement:

    expressionopt ;

    2 The expression in an expression statement is evaluated as a void expression for its side effects.

    In your case, the expression is a multiplication. This statement has no side effect, so it has no effect at all.

    If on the other hand you had this:

    i++;
    

    That's an expression that does have a side effect.

    This is also considered an expression:

    a = b * c;
    

    In this case, the side effect is the assignment operator.