In a program, we might have declared a variable as of one datatype. For some reason, we would need to have same variable in another type. For example, we may have integer type variable for storing ASCII values, whose character value needs to be displayed. This can be done without using any conversion function, instead converting integer datatype to character datatype. This type of conversion of datatype is done by using cast operator. The general syntax for casting the variable is:
(datatype name) variable_name;
#include int main() { int intVal = 97; printf("Value of intValue is %c", (char)intVal); // type casted integer to character }
Converting one datatype to another datatype is called type casting. C language implicitly performs type casting. But as a good practice, it is better to use cast operator (like above example) to convert the datatype whenever it is necessary. That means when we write above program without cast operator, it automatically converts the integer value to character value, when it sees %c in printf statement.
#include int main() { int intVal = 97; printf("Value of intValue is %c\n", intVal); // Implicit type casting of intVal is done printf("Value of intValue is %d\n", intVal); }
This type of type casting can be done with any compatible datatypes. For example, int to float and float to int, int to short int and short int to long int, short into float etc. this can be implicit by C compiler or explicit by the developer using cast operator.