When static_cast should be used?

J

Joe Gottman

Hi,

An example usage of static_cast is at
http://publib.boulder.ibm.com/infoc...oc/language/ref/clrc05keyword_static_cast.htm

But I don't understand why it is necessary to use
float d = static_cast<float>(j)/v;

Isn't
float d = float(j)/v;
enough?


It isn't strictly necessary. float d = float(j)/v works. But there are
several reasons why you should use the various *_cast operators
1) It makes clear exactly what you are doing. static_cast forces
implicit conversions (int to float for instance) which is why you use it in
your example. const_cast casts away constness. reinterpret_cast makes the
computer pretend that a variable of one type is actually of another type.
dynamic_cast is used for run-time type identification; it checks whether a
pointer to a base type is actually a pointer to the target derived type then
returns the cast pointer if it is or 0 if it is not. A plain C cast can
replace any of these except dynamic_cast, but it is helpful to you and
anyone who will have to maintain your code later to be specific about what
you are doing.

2) It is much easier, both for humans and computers, to search for
static_cast in code than to look through all the parentheses to try to
determine which are casts.

Joe Gottman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top