Skip to main content

Module assignment_in_condition

Module assignment_in_condition 

Source
Expand description

assignment-in-condition: = where the reader almost certainly meant ==.

if (x = 1) { … }          // assigns, and the condition is then 1 — always true
while (line = read()) { } // …and this one is deliberate, which is why the rule is about the *shape* below

§The shape, and the one that is excused

  reported      `if (x = 1)`, `while (x = y)`, `for (; x = y;)`   an assignment directly in the condition
  not reported  `if ((x = 1))`            the extra parentheses are the idiom that says "I meant this", and
                                          every compiler warns about it in the same way — a second pair is a
                                          deliberate choice rather than a typo
  not reported  `if (x == 1)`             a comparison
  not reported  `if (f(x = 1))`           the assignment is an argument, not the condition
  not reported  `if (x = y, x > 0)`       the condition is the comma expression, whose *last* operand is what is
                                          tested — and that operand is not an assignment

§Read as text, and why that is the honest reading here

The condition of an if is taken between its first ( and the matching ), and the question is whether that text holds a top-level =. A tree walk would have to decide which of the recovered nodes is the condition — and a condition with a mismatched parenthesis is exactly where the grammar recovers hardest. The text is what the reader wrote, and the question is about what they wrote.

Structs§

AssignmentInCondition
assignment-in-condition — see the module documentation.