Warning C26451: Arithmetic overflow: Using operator '%operator%' on a %size1% byte value and then casting the result to a %size2% byte value. Cast the value to the wider type before calling operator '%operator%' to avoid overflow

This warning indicates incorrect behavior that results from integral promotion rules and types larger than those in which arithmetic is typically performed.

We detect when a narrow type integral value was shifted left, multiplied, added, or subtracted and the result of that arithmetic operation was cast to a wider type value. If the operation overflowed the narrow type value, then data is lost. You can prevent this loss by casting the value to a wider type before the arithmetic operation.

Example 1

The following code generates this warning:

void leftshift(int i)
{
  unsigned __int64 x;
  x = i << 31;  // C26451 reported here

  // code
}

To correct this warning, use the following code:

void leftshift(int i)
{
  unsigned __int64 x;
  x = (unsigned __int64)i << 31; // OK

  // code
}

Example 2

void somefunc(__int64 y);

void callsomefunc(int x)
{
  somefunc(x * 2); // C26451 reported here

}

To correct this warning, use the following code:

void callsomefunc(int x)
{
  somefunc((__int64)x * 2); // OK
}

Example 3

__int64 add(int x)
{
  constexpr auto value = 2;
  return x += value; // C26451 reported here
}

To correct this warning, use the following code:

__int64 add(int x)
{
  constexpr auto value = 2;
  const __int64 y = (__int64)x + value; // OK
  return y;
}

See Also

ES.103: Don't overflow