Type Conversions in C
For Complete YouTube Video: Click Here
In this class, we will try to understand Type Conversions in C.
We have already covered different data types in our previous classes.
Table of Contents
Type Conversions in C
The conversions of data types are done in two different types, as shown in the image below.
Implicit Type Conversions in C
The implicit type conversion is done automatically or implicitly by the compiler.
To understand this concept, consider the following example as shown below.
For example, if we want to do the following arithmetic expression.
10 + 24.5.
Now the compiler will get confused on how to do the addition.
Here, the compiler has two possibilities: to convert the integer to a floating-point number or a floating-point number to an integer.
Guess the best and efficient method.
If we convert the floating_point number to an integer, we will lose the decimal point value.
10 + 24 = 34. This is not an efficient method.
The best way is to convert the integer to a floating-point number.
10.0 + 24.5 = 34.5.
How will the compiler make such kinds of decisions?
The image below shows how the decision is made.
The conversion is done to the rightmost data type from the above image.
To understand this consider the programming example as shown in the image below.
In the code x = x + y, we add an integer with a character.
x = 10 + ‘a’;
From the above image, the character will get converted to short int.
The output of the above expression is x = 10 + 97 = 107.
The ASCII value of ‘a’ is 97.
Explicit Type Conversions in C
Explicit type conversions are the forcible conversions of the data types in the expressions.
The operator used for explicit type conversion is ().
To understand this consider the programming example as shown in the image below.
In the above program, x is a floating-point number with a value of 24.5.
The code y = (int)x + 1; the value of x is forcibly converted into int data type.
The output of the above expression is 25.