Easy Tutorial
❮ C Exercise Example58 C Exercise Example13 ❯

Type casting is the process of converting a variable from one type to another. For example, if you want to store a long value into a simple integer, you need to cast the long type to int. You can use the type cast operator to explicitly convert a value from one type to another, like this:

(type_name) expression

Consider the following example, where the type cast operator is used to divide an integer variable by another integer variable to get 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 above code is compiled and executed, it produces the following result:

Value of mean : 3.400000

It's important to note that the precedence of the type cast operator is higher than that of division, so the value of sum is first converted to double, and then it is divided by count, resulting in a value of type double.

Type conversion can be implicit, performed automatically by the compiler, or explicit, specified using the type cast operator. Using the type cast operator when needed is a good programming practice.

Integer Promotion

Integer promotion is the process of converting integers smaller than int or unsigned int to int or unsigned int. Consider the following example, where a character is added to an integer:

Example

#include <stdio.h>

int main()
{
   int  i = 17;
   char c = 'c'; /* ascii value is 99 */
   int sum;

   sum = i + c;
   printf("Value of sum : %d\n", sum );

}

When the above code 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 before performing the addition.

Usual Arithmetic Conversion

Usual arithmetic conversion is an implicit process that forces values to a common type. The compiler first performs integer promotion. If the types of the operands are different, they are converted to the highest type in the following hierarchy:

Usual arithmetic conversion does not apply to assignment operators, 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'; /* ascii value is 99 */
   float sum;

   sum = i + c;
   printf("Value of sum : %f\n", sum );

}

When the above code 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 conversion is applied, and the compiler converts i and c to floating-point types and adds them to get a floating-point number.

❮ C Exercise Example58 C Exercise Example13 ❯