C26472 NO_CASTS_FOR_ARITHMETIC_CONVERSION

"Don't use a static_cast for arithmetic conversions. Use brace initialization, gsl::narrow_cast, or gsl::narrow."

C++ Core Guidelines: Type.1: Avoid casts

This rule helps to find places where static casts are used to convert between integral types. These casts are unsafe because the compiler would not warn if any data loss occurs. Brace initializers are better for the cases where constants are used, and a compiler error is desired. There are also utilities from the Guidelines Support Library that help to describe intentions clearly:

  • gsl::narrow ensures lossless conversion and causes run-time crash if it is not possible.
  • gsl::narrow_cast clearly states that conversion can lose data and it is acceptable.

Remarks

  • This rule is implemented only for static_casts. Using of C-style casts is generally discouraged.

Example

unhandled unexpected data

rgb from_24bit(std::uint32_t v) noexcept {
    return {
        static_cast<std::uint8_t>(v >> 16),         // C26472, what if top byte is non-zero?
        static_cast<std::uint8_t>((v >> 8) & 0xFF), // C26472
        static_cast<std::uint8_t>(v & 0xFF)         // C26472
    };
}

unhandled unexpected data – safer version

rgb from_24bit(std::uint32_t v) noexcept {
    return {
        gsl::narrow<std::uint8_t>(v >> 16),
        gsl::narrow_cast<std::uint8_t>((v >> 8) & 0xFF),
        gsl::narrow_cast<std::uint8_t>(v & 0xFF)
    };
}