What is the use of typecasting? Why is it required? Is it just to convert from one type to an开发者_StackOverflow社区other?
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);
}
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.
精彩评论