This error is caused by the syntax of the conditional-expression which is
logical-OR-expression ? expression : conditional-expression
Therefore, the part after :
must be able to parse b = 200
. However, conditional-expression
cannot parse that, because an assignment expression has less precedence - you would need to put a parenthesis around the assignment expression
a>=5 ? b=100 : (b=200);
But the fact that you need a parenthesis here does not mean that the expression otherwise is parsed as (a>=5 ? b=100 : b) = 200
, it is just a compiler's internal artefact that in the error message it talks about the left operand of assignment. The C language has the following two rules for the assignment expression syntax, and the rule that matches is applied
conditional_expression
unary_expression '=' assignment_expression
This interferes with recursive descent parsers, that would simply invoke parseConditionalExpression
, and check what token follows. Therefore some C parser implementations choose to not give a syntax error here, but parse it as though the grammar said conditional_expression '=' ...
above, and later when inspecting the parse tree, validate that the left hand side is an lvalue. For example, the Clang source code says
/// Note: we diverge from the C99 grammar when parsing the assignment-expression
/// production. C99 specifies that the LHS of an assignment operator should be
/// parsed as a unary-expression, but consistency dictates that it be a
/// conditional-expession. In practice, the important thing here is that the
/// LHS of an assignment has to be an l-value, which productions between
/// unary-expression and conditional-expression don't produce. Because we want
/// consistency, we parse the LHS as a conditional-expression, then check for
/// l-value-ness in semantic analysis stages.
And the GCC parser's source code says
/* ...
In GNU C we accept any conditional expression on the LHS and
diagnose the invalid lvalue rather than producing a syntax
error. */