description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid | |||
---|---|---|---|---|---|---|---|---|
Learn more about: Warning C26475 NO_FUNCTION_STYLE_CASTS |
Warning C26475 |
06/29/2022 |
|
|
4ed71cf8-f155-4961-b4fe-77feb3b880c3 |
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 form 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 a braced initializer if possible. If neither works, static casts may be suitable, but it's still better to use utilities from the Guidelines Support Library:
gsl::narrow
ensures lossless conversion and throwsgsl::narrowing_error
if it's not possible.gsl::narrow_cast
clearly states that conversion can lose data and it's acceptable.
-
This rule fires only for constants of primitive types. The compiler can clearly detect data loss in these cases and emits an error if a braced initializer is used. The cases that would require run-time execution are flagged by C26493 NO_CSTYLE_CAST.
-
Default initializers aren't flagged (for example
int()
).
Dangerous conversion example:
constexpr auto planck_constant = float( 6.62607004082e-34 ); // C26475
Compiler error for dangerous conversion, detecting potential data loss:
constexpr auto planck_constant = float{ 6.62607004082e-34 }; // Error C2397
To correct the dangerous conversion, use an appropriately sized primitive type:
constexpr auto planck_constant = double{ 6.62607004082e-34 };