typecasting in c

99封情书 提交于 2021-02-19 07:52:47

问题


What is the use of typecasting? Why is it required? Is it just to convert from one type to another?


回答1:


The use of type casting can be whatever your program dims necessary. For instance, in The Doryen Library, the types exposed to the user (in header files) are all void*. In the .c files they are cast to whatever is necessary, for instance to mersenne_t in the RNG toolkit. The use is obvious: mersenne_t struct contains fields that should never be messed with or even visible to the library user. Having just a TCOD_random_t type exposed to the library user results in a cleaner API.

Another example of type casting would be, for instance, rounding floats down:

float f = 1.5f;
int i = (int)f;
printf("%d",i);

The above will output 1.

You could use this to create a neat float rounding function:

float round(float f) {
    f += (f>0.0f?0.5f:(-0.5f));
    return (float)((int)f);
}



回答2:


Typecasting is a compiler construct that indicates to the parser that even though the expected type and the actual type are different, the code generator should still be able to handle it.



来源:https://stackoverflow.com/questions/4302190/typecasting-in-c

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