>
>
>
V502. The '?:' operator may not work as…


V502. The '?:' operator may not work as expected. The '?:' operator has a lower priority than the 'foo' operator.

The analyzer found a code fragment that most probably has a logic error. The program text has an expression that contains the ternary operator '?:' and might be calculated in a different way than the programmer expects.

The '?:' operator has a lower priority than operators ||, &&, |, ^, &, !=, ==, >=, <=, >, <, >>, <<, -, +, %, /, *. One might forget about it and write an incorrect code like the following one:

bool bAdd = ...;
size_t rightLen = ...;
size_t newTypeLen = rightLen + bAdd ? 1 : 0;

Having forgotten that the '+' operator has a higher priority than the '?:' operator, the programmer expects that the code is equivalent to "rightLen + (bAdd ? 1 : 0)". But actually the code is equivalent to the expression "(rightLen + bAdd) ? 1 : 0".

The analyzer diagnoses the probable error by checking:

1) If there is a variable or subexpression of the bool type to the left of the '?:' operator.

2) If this subexpression is compared to / added to / multiplied by... the variable whose type is other than bool.

If these conditions hold, it is highly probable that there is an error in this code and the analyzer will generate the warning message we are discussing.

Here are some other examples of incorrect code:

bool b;
int x, y, z, h;
...
x = y < b ? z : h;
x = y + (z != h) ? 1 : 2;

The programmer most likely wanted to have the following correct code:

bool b;
int x, y, z, h;
...
x = y < (b ? z : h);
x = y + ((z != h) ? 1 : 2);

If there is a type other than bool to the left of the '?:' operator, the analyzer thinks that the code is written in the C style (where there is no bool) or that it is written using class objects and therefore the analyzer cannot find out if this code is dangerous or not.

Here is an example of correct code in the C style that the analyzer considers correct too:

int conditions1;
int conditions2;
int conditions3;
...
char x = conditions1 + conditions2 + conditions3 ? 'a' : 'b';

This diagnostic is classified as:

You can look at examples of errors detected by the V502 diagnostic.