3

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?

  • You can replace them with `(double)` if you really want to. – Jonathan Potter Mar 26 '15 at 00:29
  • If you don't use `static_cast`, you can and should use `double(...)` instead of `(double)...`, eg: `double(3)`, `double(somevar)`, etc. – Remy Lebeau Mar 26 '15 at 00:30
  • 4
    You can also use literals: `a = 3.0 / 7.0`. – Kerrek SB Mar 26 '15 at 00:32
  • 1
    @RemyLebeau what is the difference between `double(...)` and `(double)...`? –  Mar 26 '15 at 00:35
  • One question with incompatible solutions suggested by experts, how does somebody link this question to somewhere else and feels that the answer is clear?? –  Mar 26 '15 at 00:36
  • The difference is that `double foo() / bar())` clearly does the cast on the whole expression, whereas `(double) foo()/bar()` is visually ambiguous. (And in fact casts the result of `foo` before the division; the whitespace in the example is intentionally misleading) – MSalters Mar 26 '15 at 10:40

1 Answers1

3

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;