这个错误是由条件表达式的语法引起的
logical-OR-expression ? expression : conditional-expression
因此:之后的部分必须能够解析b = 200。但是,conditional-expression 无法解析它,因为赋值表达式的优先级较低 - 您需要在赋值表达式周围加上括号
a>=5 ? b=100 : (b=200);
但您在此处需要括号这一事实确实不意味着该表达式否则会被解析为(a>=5 ? b=100 : b) = 200,它只是编译器的内部人工制品,在错误消息中它谈到了左边赋值操作数。 C语言赋值表达式语法有以下两条规则,匹配的规则适用
conditional_expression
unary_expression '=' assignment_expression
这会干扰递归下降解析器,它只会调用parseConditionalExpression,并检查后面的标记。因此,一些 C 解析器实现选择在此处不给出语法错误,而是将其解析为好像上面的语法说 conditional_expression '=' ...,然后在检查解析树时,验证左侧是左值。例如,Clang 源代码说
/// 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.
GCC 解析器的源代码说
/* ...
In GNU C we accept any conditional expression on the LHS and
diagnose the invalid lvalue rather than producing a syntax
error. */