Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to completely avoid C-style casts in C++?

Tags:

c++

c

casting

I do not believe that it is possible to completely avoid C-style casts when writing C++. I was surprised to find out that I needed to use a C-style cast to avoid a compiler truncation warning:

short value_a = 0xF00D;                     // Truncation warning in VS2008
short value_b = static_cast<short>(0xF00D); // Truncation warning in VS2008
short value_c = (short)0xF00D;              // No warning!

Are there other scenarios where there is no C++-style substitute for a C-style cast?

like image 473
sourcenouveau Avatar asked Nov 18 '10 20:11

sourcenouveau


People also ask

Why is static_cast better than C-style cast?

static_cast<>() gives you a compile time checking ability, C-Style cast doesn't. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt. Intentions are conveyed much better using C++ casts.

Can I use static_cast in C?

Static casts are only available in C++.

What is C-style cast?

C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.

Why should you use the C++ type casting features static_cast Const_cast etc rather than the old school C variety?

It helps maintain correctness, since static_cast cannot do some casts which a C-style cast can.


1 Answers

In C++, the C-style cast is defined (§5.4) in terms of C++-style casts. So for every cast you can do C-style, there's a matching C++-style cast (almost).

The "almost" is that C-style casts ignore base class accessibility. That is, there is no equivalent C++-style cast for the following:

struct foo {};
struct bar : private foo {};

bar b;
foo* f = (foo*)&b; // only way this can be done in a well-defined manner

So, no it's not strictly-speaking possible to completely ditch C-style casts. But the number of areas where a (combination of) C++-style casts doesn't suffice is few in count.


The above is the "language answer". What you're experiencing has nothing to do with C-style casts versus C++ casts, but just compiler implementation. Warnings are absolutely implementation-specific, and have nothing to do with C++.

So don't make the mistake of using your findings on this particular compiler in this particular situation for concluding things about C++ in general.

like image 101
GManNickG Avatar answered Sep 19 '22 05:09

GManNickG