Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 1.86 KB

c26472.md

File metadata and controls

51 lines (39 loc) · 1.86 KB
description title ms.date f1_keywords helpviewer_keywords ms.assetid
Learn more about: Warning C26472 NO_CASTS_FOR_ARITHMETIC_CONVERSION
Warning C26472
11/15/2017
C26472
NO_CASTS_FOR_ARITHMETIC_CONVERSION
C26472
51e215a7-0e0a-4e6c-bff1-805bf5b1af29

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