C Type Casting
Type casting is converting a variable from one type to another data type. For example, if you want to store a value of type long in a simple integer, you need to cast the long type to int. You can use thecast operatorto explicitly convert a value from one type to another, as shown below:
(type_name) expression
Look at the following example, which uses the cast operator to divide one integer variable by another to obtain a floating-point number:
Example
#include
<
stdio.h
int
main
(
)
{
int
sum
=
17
,
count
=
5;
double
mean
;
mean
=
(
double
)
sum
/
count
;
printf
(
"
Value of mean : %f
\
n
"
,
mean
)
;
}
When the code above is compiled and executed, it produces the following result:
Value of mean : 3.400000
Note here that the cast operator has higher precedence than division, so sum is first converted to double type, and then divided by count, producing a value of type double.
Type conversion can be implicit, performed automatically by the compiler, or explicit, through the use ofcast operatorto specify. In programming, it is a good habit to use the cast operator whenever type conversion is needed.
Integer promotion
Integer promotion refers to converting integer types smaller than int or unsigned int to int or unsigned int . Look at the following example, which adds a character to an int:
Example
#include
<
stdio.h
int
main
(
)
{
int
i
=
17;
char
c
= '
c
';
/*
The ASCII value is 99
*/
int
sum
;
sum
=
i
c
;
printf
(
"
Value of sum : %d
\
n
"
,
sum
)
;
}
When the code above is compiled and executed, it produces the following result:
Value of sum : 116
Here, the value of sum is 116 because the compiler performs integer promotion, converting the value of 'c' to its corresponding ASCII value when performing the actual addition.
Usual arithmetic conversions
Usual arithmetic conversionsimplicitly force values to be converted to the same type. The compiler first performsInteger promotion, and if the operand types differ, they are converted to the highest-ranking type in the following hierarchy:
Usual arithmetic conversions do not apply to the assignment operator or the logical operators && and ||. Let's look at the following example to understand this concept:
Example
#include
<
stdio.h
int
main
(
)
{
int
i
=
17;
char
c
= '
c
';
/*
The ASCII value is 99
*/
float
sum
;
sum
=
i
c
;
printf
(
"
Value of sum : %f
\
n
"
,
sum
)
;
}
When the code above is compiled and executed, it produces the following result:
Value of sum : 116.000000
Here, c is first converted to an integer, but since the final value is of type float, the usual arithmetic conversions apply: the compiler converts i and c to floating-point type and adds them to produce a floating-point number.