--- title: Warning C26451 description: "Describes the causes of MSVC code analysis warning C26451, and shows how to fix it." ms.date: 07/15/2020 f1_keywords: ["C26451", "RESULT_OF_ARITHMETIC_OPERATION_CAST_TO_LARGER_SIZE"] helpviewer_keywords: ["C26451"] --- # Warning C26451 > Arithmetic overflow: Using operator '*operator*' on a *size-a* byte value and then casting the result to a *size-b* byte value. Cast the value to the wider type before calling operator '*operator*' to avoid overflow (io.2) This warning indicates incorrect behavior that results from integral promotion rules and types larger than the ones in which arithmetic is typically performed. ## Remarks Code analysis detects when an integral value gets shifted left, multiplied, added, or subtracted, and the result gets cast to a wider integral type. If the operation overflows the narrower integral type, then data is lost. You can prevent this loss by casting the value to a wider type before the arithmetic operation. Code analysis name: `RESULT_OF_ARITHMETIC_OPERATION_CAST_TO_LARGER_SIZE` ## Example 1 The following code generates this warning: ```cpp void leftshift(int i) noexcept { unsigned __int64 x; x = i << 31; // C26451 reported here // code } ``` To correct this warning, use the following code: ```cpp void leftshift(int i) noexcept { unsigned __int64 x; x = static_cast(i) << 31; // OK // code } ``` ## Example 2 ```cpp void somefunc(__int64 /* y */) noexcept {} void callsomefunc(int x) noexcept { somefunc(x * 2); // C26451 reported here } ``` To correct this warning, use the following code: ```cpp void callsomefunc(int x) noexcept { somefunc(static_cast<__int64>(x) * 2); // OK } ``` ## Example 3 ```cpp __int64 add(int x) noexcept { constexpr auto value = 2; return x += value; // C26451 reported here } ``` To correct this warning, use the following code: ```cpp __int64 add(int x) noexcept { constexpr auto value = 2; const __int64 y = static_cast<__int64>(x) + value; // OK return y; } ``` ## See also - [ES.103: Don't overflow](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-overflow)