36

What are the differences between

int a;
// a gets some value
double pi = static_cast<double>(a)/3;

and

int a;
// a gets some value
double pi = double(a)/3;

Have you ever seen the latter? It seems to me I saw it in some snippet written by Stroustrup but I can't find the reference.

Alessandro Jacopson
  • 18,047
  • 15
  • 98
  • 153

5 Answers5

24

Someone may have thought they were constructing rather than casting. Consider:

some_fun(std::string("Hello"));

Many people think they're calling a constructor there when in fact they're doing a C-style cast. It just so happens that casting will look at constructors of the target type among the long list of other things it looks at and so here it eventually ends up invoking the constructor.

Functional notation casts have all the same weaknesses of the other kind of C cast:

  • Can inadvertently cast away constness
  • Can silently turn into a reinterpret cast
  • Are hard to differentiate with grepping tools.

Besides all that though, you're performing exactly the same operation in both cases.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
10

The latter is referred to as the functional notation of explicit casting where you explicitly say a should be treated as a double. You can pretty much cast anything to any type using this technique.

The former is the preferred way to cast a type in C++. It does basic checking to see that the type you are casting to makes sense (child class pointer to a base class pointer, etc.). In addition, like in the example you show, you can perform implicit conversions. Technically the static_cast in your example is explicit, but the result of the operation (the assignment) is implicit.

greg
  • 4,843
  • 32
  • 47
6

There is no difference in terms of generated assembly code between static_cast<double> (a) and (double) a. The key advantage of cast notation, (type_id) cast_expression, is that it is more flexible. In one situation it might be the equivalent of a const_cast, in another, a static_cast, in yet another, a dynamic_cast, in yet another, a combination of const_cast and static_cast (or dynamic_cast).

This strength is also a weakness. Cast notation means different things in different places. Another disadvantage is that it is very easy to find xxx_cast<type_id> (cast_expression). Just search for _cast. It is very hard to find expressions that use cast notation.

David Hammen
  • 32,454
  • 9
  • 60
  • 108
2

using static_cast is a safe C++-style way, but (double) - unsafe old C-style way.

see here: Type Casting

Aligus
  • 1,585
  • 1
  • 9
  • 11
1

int a;

//This is the old way of converting a variable from its type to a double
double pi = double(a)/3;

//This is the new way of converting a variable from its type to a double
double pi = static_cast<double>(a)/3;

From Walter Savitch's book, (Problem Solving with CPP, 10th Edition) page 222

Gesy Darati
  • 113
  • 1
  • 6