what is the difference between c-like casting & functional casting? [duplicate]

≡放荡痞女 提交于 2019-12-28 05:53:59

问题


Possible Duplicates:
C++ cast syntax styles
C++: What's the difference between function(myVar) and (function)myVar ?
What is the difference between (type)value and type(value) ?

b = (int) a;    // c-like cast notation
b = int (a);    // functional notation

回答1:


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.




回答2:


There's hardly any difference. Officially, the first tells the compiler that the value is an integer. This probably doesn't generate any extra code at all. The function call is an actual call that internally performs the other typecast. A smart compiler will optimize this, so they are actually the same.




回答3:


There is no difference. It is a matter of preference. These are old-style casts




回答4:


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

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



来源:https://stackoverflow.com/questions/4775781/what-is-the-difference-between-c-like-casting-functional-casting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!