What is the difference between static_cast<> and C style casting? [duplicate]
Asked Answered
I

7

292

Is there any reason to prefer static_cast<> over C style casting? Are they equivalent? Is there any sort of speed difference?

Intoxicating answered 22/10, 2009 at 18:37 Comment(1)
en.cppreference.com/w/cpp/language/explicit_castFerri
N
301

C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime.

Also, C++ style casts can be searched for easily, whereas it's really hard to search for C style casts.

Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.

When writing C++ I'd pretty much always use the C++ ones over the the C style.

Naturism answered 22/10, 2009 at 18:40 Comment(15)
The only casts that can fail at runtime are dynamic_casts.Constance
C++ reinterpret_cast<T>(U) can fail at run time pretty much the same way C style casts can, and they are all quite different from how dynamic_cast<T>(U) fails.Downbeat
­­­­­˗1 normal C cast (int)something can't fail - either you get cast to int or compiler error.Oswald
@TomášZato However, a C-style cast to a pointer or floating-point number could produce a trap representation that causes undefined behavior.Scanty
Can you elaborate why C++ casts be searched more easily than C casts?Toughminded
@MinhTran For C++ style you can search for the keyword "cast" thru out your source files. But want could you do with the c-style casts?License
@huangzonghao You can search for "(int)" or "int(". All you need to know is the type that you're searching for, which should be included anyway to filter out results. But to be honest, I don't know why this is an important feature -- I can't remember the last time I really had to search for a cast.Wagshul
@MinhTran I agree with you. I guess I never had a chance to search for those things -- The casts appear so less frequent in code that you could almost always remember where you actually casted a thing. But I think the logic here is that programmers always want to have more control over the code? So at least it make you feel better when you know you can easily find the hidden casts.License
@JohnPhuNguyen you can get a lot of false positives this way. I.e. from function prototypes or function pointer definitions and etc. Also, it'd be impossible to find just "all casts" while you can find "all reinterpret_casts" and analyze them.Eddie
I just went through this the other day, where I changed ALL C-style casts to C++ casts. That was a big pain finding all of the various possible variations of data types and whitespace inside and surrounding the parenthesis. A simple search-and-replace is not easy.Stupor
@RemyLebeau Use an editor with regex search&replace and you won't have to worry about whitespaces anymore.Gillan
@Gillan I was using a regex search at the time. It was still a huge PITA to do. And here I am, months later, still finding cases that I missed the first time around.Stupor
C styles are checked by compiler, too. I think there is no difference between static_cast and c style casts.Cowpox
What are the "4 different C++ style casts"?Glyptograph
riptutorial.com/cplusplus/example/19819/c-style-casting "It's better to use new c++ cast, because s more readable and can be spotted easily anywhere inside a C++ source code and errors will be detected in compile-time, instead in run-time. As this cast can result in unintended reinterpret_cast, it is often considered dangerous."Impersonate
I
232

In short:

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

More Explanation:

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.

char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a pointer to a 4-byte type, pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

You can also check this page on more explanation on C++ casts : Click Here

Imogen answered 22/10, 2009 at 18:37 Comment(4)
I think instead of "4-byte pointer" you meant "pointer to 4-byte datatype"Chainsmoke
but it allows int q = static_cast<int>(c);Hirsh
@Hirsh That's because there's nothing wrong with that line.Gamboa
@Hirsh in this case, it will have the same effect as an implicit conversion in int q = c;. The type of the initialized variable dominates and the initializer is converted to the that type. Hence, the c will be promoted to int and then this result will be used to initialize the q.Sipes
B
18

See A comparison of the C++ casting operators.

However, using the same syntax for a variety of different casting operations can make the intent of the programmer unclear.

Furthermore, it can be difficult to find a specific type of cast in a large codebase.

the generality of the C-style cast can be overkill for situations where all that is needed is a simple conversion. The ability to select between several different casting operators of differing degrees of power can prevent programmers from inadvertently casting to an incorrect type.

Byssus answered 22/10, 2009 at 18:41 Comment(0)
C
15
struct A {};
struct B : A {};
struct C {}; 

int main()
{
    A* a = new A;    

    int i = 10;

    a = (A*) (&i); // NO ERROR! FAIL!

    //a = static_cast<A*>(&i); ERROR! SMART!

    A* b = new B;

    B* b2 = static_cast<B*>(b); // NO ERROR! SMART!

    C* c = (C*)(b); // NO ERROR! FAIL!

    //C* c = static_cast<C*>(b); ERROR! SMART!
}
Cerebrovascular answered 16/4, 2015 at 11:10 Comment(2)
Could you please elaborate more your answer adding a little more description about the solution you provide?Kariekaril
I think the answer shows that "static_casts" checks for type conversions to make sure they are along valid paths in the hierarchy graph. In this particular example, casting from A* to B* or B* to A* is allowed because A and B form a path in the hierarchical graph. C* is not on the path so static_cast will produce compile-time error. Sidenote: It may be worth noting that casting from A* to B* may result in NULL with a dynamic_cast at run time depending on the true underlying object.Baber
G
13

A great post explaining different casts in C/C++, and what C-style cast really does: https://anteru.net/blog/2007/12/18/200/index.html

C-Style casting, using the (type)variable syntax. The worst ever invented. This tries to do the following casts, in this order: (see also C++ Standard, 5.4 expr.cast paragraph 5)

  1. const_cast
  2. static_cast
  3. static_cast followed by const_cast
  4. reinterpret_cast
  5. reinterpret_castfollowed by const_cast
Gabey answered 15/12, 2017 at 19:23 Comment(1)
Great post. But it's quite old(2007). Is there anything that needs to be updated in the example in that post?Begley
J
5

Since there are many different kinds of casting each with different semantics, static_cast<> allows you to say "I'm doing a legal conversion from one type to another" like from int to double. A plain C-style cast can mean a lot of things. Are you up/down casting? Are you reinterpreting a pointer?

Jackfruit answered 22/10, 2009 at 18:40 Comment(0)
S
5

static_cast checks at compile time that conversion is not between obviously incompatible types. Contrary to dynamic_cast, no check for types compatibility is done at run time. Also, static_cast conversion is not necessarily safe.

static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int.

The user of static_cast must make sure that the conversion is safe.

The C-style cast does not perform any check, either at compile or at run time.

Sawyor answered 1/5, 2015 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.