21

Consider:

b = (int) a;    // C-like cast notation
b = int (a);    // Functional notation
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nnkk
  • 211
  • 1
  • 2
  • 3

3 Answers3

8

Apparently I was wrong in my initial cut at an answer. They are roughly equivalent. And while compound type names like long long or void * can't use functional syntax directly (i.e. long long(val) doesn't work), using typedef can get around this issue.

Both cast notations are very bad and should be avoided. For example:

const char c = 'a';
void *fred = (void *)(&c);

works, and it shouldn't.

Both the C-style cast notation will sometimes behave like static_cast, sometimes like const_cast, sometimes like reinterpret_cast, or even a combination of the two depending on the exact situation in which it's used. These semantics are rather complex and it's not always easy to tell exactly what's happening in any given situation.

I have gone to using mostly C++ static_cast<type>(val) style casts, and never use C-style casts. Based on my research for this question I'm going to also stop using function-style casts for anything. The question "C++ cast syntax styles" has an excellent answer (the accepted one) that details why.

Community
  • 1
  • 1
Omnifarious
  • 54,333
  • 19
  • 131
  • 194
  • 5
    This is completely false. `class A { operator int() const; }; int test( A a ) { return int(a); }` works perfectly even though `int` has no constructor. A function style cast with a single parameter has exactly the same effect as the equivalent C-style cast. – CB Bailey Jan 23 '11 at 19:19
  • @Charles Bailey - I read more and found out I was wrong. :-) I fixed my answer. – Omnifarious Jan 23 '11 at 19:21
  • Functional style cast with pointers: `typedef void * voidp; voidp fred = voidp(&c);` – Benjamin Lindley Jan 23 '11 at 19:24
  • @PigBen - Oh, you're right. *sigh* Fixed my answer yet again. I hate when people use typedefs to obscure the fact a type is a pointer. :-( – Omnifarious Jan 23 '11 at 19:31
  • @Omnifarious: I do too. I was just showing a way the cast could be done. – Benjamin Lindley Jan 23 '11 at 19:34
  • @PigBen - *nod* I realize. I was explaining why I didn't think of it. :-) – Omnifarious Jan 23 '11 at 19:35
2

There isn't any difference. It is a matter of preference. These are old-style casts.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cratylus
  • 52,998
  • 69
  • 209
  • 339
0

It depends where you use it and how. I.e. if you have values or pointers (or pointers of pointers).

With C++ you should read up on *_cast<> and use them instead.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
stefan
  • 2,886
  • 21
  • 27