jackhab
jackhab

Reputation: 17708

Is it OK to use C-style cast for built-in types?

After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?

Upvotes: 19

Views: 10315

Answers (9)

tragomaskhalos
tragomaskhalos

Reputation: 2753

I can think of one legitimate use for a C-style cast:

// cast away return value to shut up pedantic compiler warnings
(void)printf("foo\n");

Upvotes: 3

JohnMcG
JohnMcG

Reputation: 8815

I would not, for the following reasons:

  • Casts are ugly and should be ugly and stand out in your code, and be findable using grep and similar tools.
  • "Always use C++ casts" is a simple rule that is much more likely to be remembered and followed than, "Use C++ casts on user-defined types, but it's OK to use C-style casts on built-in types."
  • C++ style casts provide more information to other developers about why the cast is necessary.
  • C-style casts may let you do conversions you didn't intend -- if you have an interface that takes in (int*) and you were using c-style casts to pass it a const int*, and the interface changes to take in a long*, your code using c-style casts will continue to work, even if it's not what you wanted.

Upvotes: 19

hyde
hyde

Reputation: 62848

The one case where I prefer legacy C cast is casting byte buffers to different signedness. Many APIs have different conventions, and there is no "right answer" really, and the cast is not dangerous in the context it is done, where code needs to be only as platform-agnostic as the combination of libraries being used.

A concrete example for what I mean, I think this is just fine:

unsigned char foo[16];
lib1_load_foo(key);
lib2_use_foo((char*)key);

But for anything else, if cast is needed, it is going to have potential side-effects, which should stand out, and using C++ style (arguably ugly) cast is the right choice. And if cast is not needed, then don't use cast.

Upvotes: 0

zwol
zwol

Reputation: 140748

If you are casting from a numeric type, to another numeric type, then I think C-style casts are preferable to *_cast. Each of the *_cast operators has a specific reason not to use it on numeric types:

  • reinterpret_cast, when applied to numeric types, does a normal numeric conversion rather than reinterpreting the bits, i.e. writing reinterpret_cast<uint64_t>(3.14159) does not produce the integer with the same bit representation as that floating-point constant. This is contrary to intuition.
  • const_cast is never necessary on a numeric value, and if applied to a numeric variable (as opposed to a pointer or reference to a number), suggests that the type of that variable is incorrect.
  • dynamic_cast just plain doesn't make sense on numbers because numbers never have dynamic type.
  • static_cast is normally used on class types. Therefore it looks strange to apply static_cast to a number; your readers will scratch their heads and wonder if there's something they don't know about static_cast that makes it different from the C-style cast when applied to a number. (In fact, they are identical, but I had to read the relevant C++ spec section a couple times to be sure they were identical, and I still have the "something weird must be going on here" reaction.)

and there is an additional stylistic reason to avoid them:

  • If you need to cast among numeric types, you are likely to need to do several of them in a cluster; because of that, the concision of C-style casts is important. For instance, the program I'm writing right now has a whole bunch of this sort of thing:

    uint32_t n = ((uint32_t(buf[0]) << 24) |
                  (uint32_t(buf[1]) << 16) |
                  (uint32_t(buf[2]) <<  8) |
                  (uint32_t(buf[3])      ));
    

    Using static_cast here would obscure the arithmetic, which is the important thing. (Note: those casts are unnecessary only if sizeof(uint32_t) <= sizeof(unsigned int), which is a safe assumption nowadays but I still prefer the explicitness.) (Yes, I probably ought to factor out this operation into a be32_to_cpu inline helper, but I'd still code it the same way.)

Upvotes: 12

user379529
user379529

Reputation: 41

In my opinion C-Style casting of built in types when using standard library functions and STL is ok, and results in easier to read code.

In the company I work in we compile with maximum (level 4) warnings, so we get warnings about every little type cast etc... So I use c-style casts in these because they're small, not so verbose and make sense.

for (int i = 0; i < (int)myvec.size(); i++)
{
  // do something int-related with i
}
float val = (float)atof(input_string);

etc....

But if its on (eg library) code that may change, then static_cast<>() is better because you can ensure the compiler will error out if types change and the cast no longer makes sense. Also, its impossible to search for casts within code if you only use c-style. "static_cast<mytype>(" is pretty easy to search for. :)

Upvotes: 4

Johan Kotlinski
Johan Kotlinski

Reputation: 25749

I think it may be OK given the context. Example:

/* Convert -1..1 to -32768..32767 */
short float_to_short(float f)
{
    return (short)(max(-32768.f, min(32767.f, f * 32767.f)));
}

Upvotes: 3

David Thornley
David Thornley

Reputation: 57046

Why do you need that particular cast? Any numeric type can be converted to a long without a cast (at potential loss of precision), so casting doesn't let the compiler do anything it can't already. By casting, all you do is remove the compiler's ability to warn if there is a potential problem. If you're converting some other basic type (like a pointer), to a long, I'd really like to see a reinterpret_cast<> rather than a C-type cast, so I can find what's going on easily if there turns out to be a problem.

I'm not going to approve of casting without a reason, and I'm certainly not going to approve of C-type casts without a good reason. I don't see a reason to cast between most built-in types, and if there is one I want to be able to find it easily with a text search.

Upvotes: 0

anon
anon

Reputation:

If you find you need to do a C-style cast (or a reinterpret_cast) then look very carefully at your code it is 99.99% certain there is something wrong with it. Both these casts leed almost inevitably to implementation specific (and very often undefined) behaviour.

Upvotes: -1

Konrad Rudolph
Konrad Rudolph

Reputation: 545865

Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?

Don't use them, ever. The reasons against using them applies here as well. Basically, once you use them, all bets are off because the compiler won't help you any more. While this is more dangerous for pointers than for other types, it's potentially still dangerous and gives poor compiler diagnostics in the case of errors, whereas new style casts offer richer error messages since their usage is more constrained: Meyers cites the example of casting away constness: using any cast other than const_cast won't compile, thus making it clear what happens here.

Also, some other disadvantages apply regardless of the types, namely syntactic considerations: A C-style cast is very unobtrusive. This isn't good: C++ casts stand out clearly in the code and point to potentially dangerous code. They can also easily be searched for in IDEs and text editors. Try searching for a C-style cast in a large code and you'll see how hard this is.

On the other hand, C-style casts offer no advantages over C++ casts so there's not even a trade-off to consider.

More generally, Scott Meyers advises to “Minimize casts” in Effective C++ (item 27), because “casts subvert the type system.”

Upvotes: 29

Related Questions