In this tutorial, we are going to learn about type conversions in the C language.

When an operator has operands of different types, it is referred to as mixed mode. C supports the use of mixed-mode operations in expressions.  For an operation to take place, both the operands must be of the same type.

C Type Conversions:

Type conversion is performed to convert one or both the operands to an appropriate data type before evaluation.

Type conversion means converting one data type value into another data type value. There are two types of type conversions:

  • implicit conversion (also called type coercion)
  • explicit conversion (also called type casting)

Implicit Type Conversions:

In the case of implicit type conversions, the compiler automatically converts one data type value into another data type value. It is also known as Automatic type conversion.

Implicit type conversions can occur during an assignment or while using any other operators. During the assignment, the R-value is converted to the type of L-value.

For example, in the statement

int a = 17.35;

17.35 which is the value on the right-hand side, is automatically converted into an int type as 17.

When values of different data types are used in arithmetic, relational and logical operators, the value of the lower size data type is converted automatically into the data type of the higher size before the evaluation.

The conversion order is:

bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double

Explicit Type Conversions:

A programmer can instruct the compiler to explicitly convert a value of one type to another using a typecast operator.

When a typecast operator is used explicitly, the type conversion process is called explicit type conversion or typecasting. This is user-defined.

The syntax for using a typecast operator is:

( data_type ) expression

where the expression is converted to the target data_type enclosed within the parentheses.

Here, the expression may contain constants or variables and the data_type must be a primitive data type or void.

For example, the expression

(float) 1 / 3 is evaluated as 1.0 / 3

yielding 0.333333, whereas 1 / 3 yields 0

In the expression ((int)num)%2, if num is a float variable with value 5.5, then the expression evaluates to 1.

For example, let us understand the following code:

#include <stdio.h>
void main () {
     float a, b;
     a = 35 / 17;
     b = (float) 35 / 17;
     printf("a = %f, b = %f\n", a, b);
}

output:

a = 2.000000, b = 2.058824

References:

Happy Learning 🙂