Warning C26472

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 wouldn't 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 throws gsl::narrowing_error if it's not possible.
  • gsl::narrow_cast clearly states that conversion can lose data and it's acceptable.

Remarks

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

Code analysis name: NO_CASTS_FOR_ARITHMETIC_CONVERSION

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)
    };
}