Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 1.86 KB

File metadata and controls

51 lines (39 loc) · 1.86 KB
description Learn more about: Warning C26472 NO_CASTS_FOR_ARITHMETIC_CONVERSION
title Warning C26472
ms.date 11/15/2017
f1_keywords
C26472
NO_CASTS_FOR_ARITHMETIC_CONVERSION
helpviewer_keywords
C26472
ms.assetid 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)
    };
}