38

A question related to Regular cast vs. static_cast vs. dynamic_cast:

What cast syntax style do you prefer in C++?

  • C-style cast syntax: (int)foo
  • C++-style cast syntax: static_cast<int>(foo)
  • constructor syntax: int(foo)

They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).

If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.

What do you think?

Community
  • 1
  • 1
palm3D
  • 7,970
  • 6
  • 28
  • 33
  • 1
    Does this answer your question? [When should static\_cast, dynamic\_cast, const\_cast and reinterpret\_cast be used?](https://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used) – SuperStormer Jan 02 '22 at 07:28

10 Answers10

61

It's best practice never to use C-style casts for three main reasons:

  • as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing
  • the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing.
  • this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible.

As palm3D noted:

I find C++-style cast syntax too verbose.

This is intentional, for the reasons given above.

The constructor syntax (official name: function-style cast) is semantically the same as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate:

void f(auto_ptr<int> x);

f(static_cast<auto_ptr<int> >(new int(5))); // GOOD
f(auto_ptr<int>(new int(5));                // BAD

The static_cast here will actually call the auto_ptr constructor.

Andrew
  • 5,212
  • 1
  • 22
  • 40
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 15
    I wonder how many times have you searched for a cast in your code with an automated tool... – Blindy Dec 05 '10 at 05:08
  • 2
    @Blindly: it happens. I have already done that. Remember that in C++, unlike some other languages (Java, C#), you can usually program without casts. Every explicit cast in your code is a potential design flaw. Identifying casts in your C++ code is an important step in refactoring. In C# it would of course be ridiculous to search for casts in code – they’re everywhere! – Konrad Rudolph Dec 05 '10 at 10:30
  • @Konrad: And, of course, both Java *and* C# also have their own `dynamic_cast` equivalent which is a special cast. – Puppy May 28 '12 at 21:41
  • "which of the various casts is used". that's a simple one. it always uses a c style cast. no need trying to translate it to a c++ style cast – Johannes Schaub - litb Oct 19 '12 at 20:04
  • in the auto_ptr example, isn't the "bad" call constructing a temp auto_ptr, rather than attempting to cast the pointer? – user666412 Dec 03 '13 at 15:35
  • @user666412 I think you misunderstand what a cast does: it also creates a temporary `auto_ptr`. A cast is nothing special in this regard, only the syntax changes. – Konrad Rudolph Dec 03 '13 at 16:25
  • 3
    There are two problems with your answer: 1) you mention "two main reasons" but you list three. :) +1 – augustin Sep 22 '15 at 01:42
  • 7
    Isn't the `// GOOD` actually nonsense here? It'd be quite awful to write something like `static_cast("hello")` instead of `std::string("hello")` or any similar construction of object of user type. – Ruslan Jan 08 '16 at 13:47
  • @Ruslan Well several C++ authorities disagree with you. – Konrad Rudolph Jan 09 '16 at 01:43
  • 3
    Then someone should have no problem citing precisely where and with what wording (a) Sutter and (b) the rest of the "several C++ authorities" said anything of the sort, because it sounds like (i) news and (ii) nonsense to me. – underscore_d Sep 12 '18 at 19:03
  • @underscore_d I did cite one of these authorities in my answer. For what it’s worth the style certainly hasn’t caught on, and is also somewhat obsolete with uniform initialisation. – Konrad Rudolph Sep 12 '18 at 19:07
  • That's a relief! What I was hoping was that the section where Sutter said that was excerpted somewhere so that I could read his reasoning, but I'm guessing not? (at least not all these years/editions later) That or another actual, specific citation. But yeah, it doesn't matter if it's rightly superseded. – underscore_d Sep 13 '18 at 09:38
  • One very good reason to avoid functional style casts is the most vexing parse. Consider this: `int a = 42; MyDoubleClass d(double(a));` What is `d`? Answer: A function called `d` that takes a `double` as a parameter and returns an object of type `MyDoubleClass`. – callyalater Dec 11 '18 at 22:21
16

According to Stroustrup:

The "new-style casts" were introduced to give programmers a chance to state their intentions more clearly and for the compiler to catch more errors.

So really, its for safety as it does extra compile-time checking.

hometoast
  • 11,522
  • 5
  • 41
  • 58
8

Regarding this subject, I'm following the recommandations made by Scott Meyers (More Effective C++, Item 2 : Prefer C++-style casts).

I agree that C++ style cast are verbose, but that's what I like about them : they are very easy to spot, and they make the code easier to read (which is more important than writing).

They also force you to think about what kind of cast you need, and to chose the right one, reducing the risk of mistakes. They will also help you detecting errors at compile time instead at runtime.

Jérôme
  • 26,567
  • 29
  • 98
  • 120
4

Definitely C++-style. The extra typing will help prevent you from casting when you shouldn't :-)

Ben Collins
  • 20,538
  • 18
  • 127
  • 187
3

I use static_cast for two reasons.

  1. It's explicitly clear what's taking place. I can't read over that without realizing there's a cast going on. With C-style casts you eye can pass right over it without pause.
  2. It's easy to search for every place in my code where I'm casting.
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
3

The constructor syntax. C++ is OO, constructors exist, I use them. If you feel the need to annotate these conversion ctor's you should do it for every type, not just the built-in ones. Maybe you use the 'explicit' keyword for conversion ctors but the client syntax mimics exactly what the ctor syntax for built-in types does. Being greppable, that may be true, but what a big surprise that typing more characters makes searches easy. Why treat these ones as special? If you are writing math formulas with lots of int/unsigned/... to and from double/float - graphics - and you need to write a static_cast every time, the look of the formula gets cluttered and is very much unreadable. And it's an uphill battle anyway as a lot of times you will convert without even noticing that you are. For downcasting pointers I do use the static_cast as of course no ctor exists by default that would do that.

QBziZ
  • 3,170
  • 23
  • 24
1

C-style cast syntax, do not error check. C++-style cast syntax, does some checking. When using static_cast, even if it doesn't do checking, at least you know you should be carefull here.

CiNN
  • 9,752
  • 6
  • 44
  • 57
  • 1
    `static_cast` always checks that the source and destination types are compatible. (It can't protect users against their mistake if they convert a base to a derived type that it doesn't really have, but that's their fault.) – underscore_d May 12 '17 at 23:42
1

C-style cast is the worst way to go. It's harder to see, ungreppable, conflates different actions that should not be conflated, and can't do everything that C++-style casts can do. They really should have removed C-style casts from the language.

DrPizza
  • 17,882
  • 7
  • 41
  • 53
1

We currently use C-style casts everywhere. I asked the other casting question, and I now see the advantage of using static_cast instead, if for no other reason than it's "greppable" (I like that term). I will probably start using that.

I don't like the C++ style; it looks too much like a function call.

Community
  • 1
  • 1
Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121
  • 1
    looking like a function call can be nice, it allows you to have utility functions which share the same style such as the common `lexical_cast` for converting from strings <-> numeric types. But that's just an opinion. – Evan Teran Apr 04 '10 at 05:06
1

Go for C++ style and, at worse, the ugly verbose code snippets that comprised C++'s explicit typecast will be a constant reminder of what we all know (i.e explicit casting is bad -- the lead to the coin-ing of expletives). Do not go with C++ style if you want to master the art of tracking runtime errors.

CAH
  • 11
  • 1