Why aren't typedefs strongly typed?

独自空忆成欢 提交于 2019-12-14 00:23:12

问题


What's the reason for typedefs not being strongly typed? Is there any benefit I can't see or is it due to backward compatibility? See this example:

typedef int Velocity;
void foo(Velocity v) {
    //do anything;
}
int main() {
    int i=4;
    foo(i); //Should result in compile error if strongly typed.
    return 0;
}

I am not asking for workarounds to get a strong typed datatype but only want to know why the standard isn't requiring typedefs to be strongly typed?

Thank you.


回答1:


Because C is not strongly typed and typedef has its origin in that thinking

typedef is just for convenience and readability, it doesn't create a new type.




回答2:


typedef is just a missnomer (like many other keywords). Think of it as typealias.

C has in the contrary a whole idea of what compatible types are. This allows for example to link compilation units together, even if declarations of function protopyes are only done with compatible types and not with identical ones. All this comes from simple practical necessity in every day life, being still able to give some guarantees to implementations.




回答3:


Even if Velocity were a distinct type from int, your code would compile and work just fine due to type conversion rules. What would not work is passing an expression of type Velocity * to a function expecting int *, etc. If you want to achieve the latter form of type enforcement, simply make Velocity a structure or union type containing a single integer, and you'll now have a new real type.



来源:https://stackoverflow.com/questions/8182910/why-arent-typedefs-strongly-typed

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