8-Type Conversion in C
8-Type Conversion in C
In C, type conversion refers to the process of converting one data type to another. It can be done automatically by the compiler or
manually by the programmer. The type conversion is only performed to those data types where conversion is possible.
#include <stdio.h>
int main() {
float f1 = 5.5;
int a;
Output
a: 5
f1: 5.500000
f2: 5.000000
Explanation: In the above program, when f1 is assigned to int a, its value is automatically converted to integer first and then assigned
to a. On the other hand, we manually convert the value of a to assign it to float variable f2.
The automatic type conversion performed by the compiler is called Implicit Type Conversion and the manual one done by the
programmer is called Explicit Type Conversion.
For example, if an integer is added to a float, the integer is implicitly converted to a float, and the result is a float.
Example
#include <stdio.h>
int main() {
int n1 = 5;
float n2 = 4.5;
printf("%.2f\n", result);
return 0;
}
Output
9.50
Explanation: In this code, implicit type conversion occurs when n1 (int) is automatically converted to a float during the expression n1 +
n2 to match the type of n2.
Note: It is possible for type conversions to lose information. Signs can be lost when signed is implicitly converted to unsigned, and
overflow can occur when long is converted to float.
1. Conversion Rank:
Refers to the priority assigned to data types during conversions, where types with higher rank (e.g., double) are converted to lower
rank types (e.g., int) only when necessary.
2. Conversions in Assignment Expressions:
Occurs when a value is assigned to a variable of a different type, e.g., assigning a float to an int results in truncation of the decimal
part.
3. Conversion in Other Binary Expressions:
Happens when operators are used on operands of different types. The compiler converts them to a common type for compatibility (e.g.,
adding an int to a float).
4. Promotion:
Involves converting a smaller data type to a larger one (e.g., int to float).
5. Demotion:
Converts a larger data type to a smaller one (e.g., float to int), often leading to loss of precision or data truncation.
Syntax
(type) expression
where type indicates the final data type to which the expression is converted.
Example
#include <stdio.h>
int main() {
float n1 = 7.9;
int n2;
printf("%d", n2);
return 0;
}
Output