V559. Suspicious assignment inside the condition expression of 'if/while/for' operator

27.05.2011

The analyzer detected an issue when an 'if' or 'while' operator's condition contains the assignment operator '=' while the variable is assigned a constant value. Such a construct usually signals an error. It is highly probable that the programmer intended to use the '==' operator instead of '='.

Consider this sample:

const int MAX_X = 100;
int x;
...
if (x = MAX_X)
{ ... }

There is a misprint in the code. Instead of comparing the 'x' variable with the MAX_X constant, the value of the 'x' variable will be changed. This is the correct code:

if (x == MAX_X)
{ ... }

If a variable is assigned a non-constant value, the V559 warning will not be generated. Assignment inside a condition is a frequent method to abridge the code. Here is a code sample the analyzer considers safe:

while (x = get())
{
  ...
}
You can look at examples of errors from real projects which were detected by this diagnostic message.