简体   繁体   中英

are static_cast<double> and double the same?

I am a beginner in C++ casting. I need to know are static_cast<double> and double ex-changable in any code?

In the following code can I replace static_cast<double> with double ? which is much shorter. Do I loose any readability?

a= static_cast<double> ( 3 ) / static_cast<double>( 7 );

How about static_cast of other basic types such as int , char , size_t ?

According to explanations they must be the same. But is there any exceptional case?

Just read When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?


The C++11 draft standard calls T(number) functional notation and (T) number cast notation. Given that the expression list is a single expression, they're equivalent:

§5.2.3/1 A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4). [...]

(T) number can call static_cast , which has the following behavior in this situation:

§5.2.9/4 Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.

You could save yourself a lot of typing and just use floating literals (which has type double).

a = 3.0 / 7.0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM