Reputation: 18603
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.
Upvotes: 40
Views: 36998
Reputation: 113
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
Upvotes: 1
Reputation: 4953
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.
Upvotes: 11
Reputation: 33116
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.
Upvotes: 5
Reputation: 40859
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:
Besides all that though, you're performing exactly the same operation in both cases.
Upvotes: 25
Reputation: 1605
using static_cast is a safe C++-style way, but (double) - unsafe old C-style way.
see here: Type Casting
Upvotes: 2