Type Conversion in C Language:
Type Conversion and Typecasting
Type conversion and typecasting in C are used to convert one data type into another. This can be done automatically by the compiler (implicit conversion) or manually by the programmer (explicit conversion).
Automatic Type Conversion
Automatic type conversion, also known as implicit type conversion or coercion, occurs when the compiler automatically converts one data type into another. This typically happens when performing operations on different data types.
Rules of Automatic type conversion
- When an integer and a floating-point number are used in an operation, the integer is converted to a floating-point number.
- When performing operations with different sizes of integers, the smaller integer is converted to the larger integer type.
- Characters are converted to integers when used in arithmetic operations.
For example:
#include
int main() {
int a = 5;
float b = 2.5;
float result = a + b; // 'a' is implicitly converted to float
printf("Result: %f\n", result);
return 0;
}
Typecasting
Typecasting, also known as explicit type conversion, is performed by the programmer to convert one data type into another. This is done using the cast operator. The syntax for typecasting is:
(type) expression
For example:
#include
int main() {
int a = 5;
float b = 2.5;
int result = a + (int)b; // 'b' is explicitly converted to int
printf("Result: %d\n", result);
return 0;
}
Rules of Typecasting
- When typecasting from a higher data type to a lower data type, there may be a loss of data. For example, converting a float to an int will truncate the decimal part.
- Typecasting does not change the actual data type of the variable, it only changes the way the data is interpreted during the operation.
- Typecasting can be used to forcefully change the type of a variable, which can be useful in certain situations.
Examples
Here are some examples of type conversion and typecasting:
#include
int main() {
// Automatic Type Conversion
char c = 'A';
int i = c; // 'c' is implicitly converted to int
printf("Character to integer: %d\n", i);
float f = 3.14;
double d = f; // 'f' is implicitly converted to double
printf("Float to double: %f\n", d);
// Typecasting
double pi = 3.14159;
int truncated_pi = (int)pi; // 'pi' is explicitly converted to int
printf("Double to int: %d\n", truncated_pi);
int x = 10;
int y = 3;
float division = (float)x / y; // 'x' is explicitly converted to float
printf("Integer division with typecasting: %f\n", division);
return 0;
}