Skip to content

Latest commit

 

History

History
43 lines (32 loc) · 1.81 KB

c26475.md

File metadata and controls

43 lines (32 loc) · 1.81 KB
description title ms.date ms.topic f1_keywords helpviewer_keywords ms.assetid
Learn more about: C26475 NO_FUNCTION_STYLE_CASTS
C26475
11/15/2017
conceptual
C26475
C26475
4ed71cf8-f155-4961-b4fe-77feb3b880c3

C26475 NO_FUNCTION_STYLE_CASTS

"Do not use function style C-casts."

C++ Core Guidelines: ES.49: If you must use a cast, use a named cast

Function-style casts (for example, int(1.1)) are another incarnation of C-style casts (like (int)1.1), which have questionable safety. Specifically, the compiler doesn’t try to check if any data loss can occur either in C-casts or in function casts. In both cases, it's better either to avoid casting or to use brace initializer if possible. If neither works, static casts may be suitable, but it is still better to use utilities from the Guidelines Support Library:

  • 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 fires only for constants of primitive types. These are the cases where compiler can clearly detect data loss and emit error if brace initializer is used. The cases that would require run-time execution are flagged by C26493 NO_CSTYLE_CAST.
  • Default initializers are not flagged (for example int()).

Example

dangerous conversion

constexpr auto planck_constant = float( 6.62607004082e-34 ); // C26475
dangerous conversion – detecting potential data loss
constexpr auto planck_constant = float{ 6.62607004082e-34 }; // Error C2397
dangerous conversion – corrected
constexpr auto planck_constant = double{ 6.62607004082e-34 };