Type casting is the process of converting one data type to another by the programmer, using the casting operator.
Syntax
In C, this would be with brackets like the following:
int x;
double y;
y = (double) x;Note that in the above, not casting x would not be a compiler error, since casting from an int to a double is not destructive. It is however good practice, and some other cases would require it, most commonly the void pointer type:
void* x;
*x; //You cannot dereference a null pointer, this is a compilation error!
// Instead, cast the pointer to the type it's supposed to be:
int* y;
y = (int*) x;Extra Info
It’s technically a compiler error only if you pass the compiler flag Werror that makes every C warning into an error, but everyone and their mothers use that flag, especially in an academic setting.
Rules
For numerical values, type casting also follows a specific set of rules:
- If the original type is unsigned, and it is typecasted to a larger signed type, the value is promoted without sign extension.
- If the original type is signed, and is typecasted to a larger signed type, the sign is extended. I.e if the leftmost bit is 1, the rest is filled with ones.