>
>
>
V1012. The expression is always false. …


V1012. The expression is always false. Overflow check is incorrect.

The analyzer has detected an incorrect check for an overflow that may occur when adding variables of type 'unsigned short' or 'unsigned char'.

Consider the following example of incorrect code:

bool IsValidAddition(unsigned short x, unsigned short y)
{
  if (x + y < x)
    return false;
  return true;
}

When adding two variables of type 'unsigned short', both are cast to type 'int'. The resulting value will also be of type 'int'. Because of that, no matter what values are stored in the variables 'x' and 'y', adding them will never cause an overflow. The comparison operation is executed next, with the right operand (the 'x' variable) promoted to type 'int' again. Therefore, the code above is equivalent to this:

bool IsValidAddition(unsigned short x, unsigned short y)
{
  if ((int)(x) + (int)(y) < (int)(x))
    return false;
  return true;
}

The "x + y < x" expression turns out to be always false. The compiler will most likely optimize the function by substituting the 'true' value in every call to it. This means that the function does not actually check anything and does not protect your program from an overflow.

Note: if you use the data model where the types 'short' and 'int' are the same size, the check will work correctly and the analyzer will ignore it.

To fix the check, you have to explicitly cast the sum of the two variables to type 'unsigned short':

if ((unsigned short)(x + y) < x)
{
  ...
}

This diagnostic is classified as: