Link to home
Start Free TrialLog in
Avatar of larockd
larockd

asked on

When To Use static_cast as opposed to traditional methods

C++ introduced the use of new casting operators.    In a book I am reading I have came across
static_cast as a way to convert types to other types.  Previously I would  use the following method of
casting.

while ((!isspace(pBuffer[location])) && ((unsigned int)location < strlen(pBuffer)))

Should I abandon the above method of casting for the static_cast method used
below.

while ((!isspace(pBuffer[location])) && (static_cast<unsigned int>(location) < strlen(pBuffer)))

What are the advantages of using static_cast as opposed to direct casting as
in the first line of code?  Are there any advantages to using the former casting method I was used to.

Thanks For The Input.
Darrell
Avatar of q2guo
q2guo

static_cast has basically the same power and meaning as the general-purpose c-style cast.  If you are programming in C++
you should abandon the old style C cast.  Also, the new style
cast in C++ is easier to indentify.
Avatar of larockd

ASKER

I want to know what the advantages are.  Why did they create static_cast and abandoned the old casting style.  What are the benefits.  

As in my question I posed these questions which were not answered in your proposed answer
What are the advantages of using static_cast as opposed to direct casting as
in the first line of code?  Are there any advantages to using the former casting method I was used to.
ASKER CERTIFIED SOLUTION
Avatar of q2guo
q2guo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As q2quop said, the new static cast is FUNCTIONALLY identical to the old cast.  That is, it produces the same result.  However there is an important difference.  It stands out (it is ugly as sin.)  This can makes sure that people reading the code don't miss it by mistake.  The old cast just consists of a type name and parenthesis and in a complex expression can easily be missed.

In most cases, I prefer the old cast myself, unless it looks like it is going to get burried.
Avatar of larockd

ASKER

Thanks For the input..