Type conversion (also known as type casting) in C refers to converting a variable from one data type to another.
C supports two types of type conversion:
- Implicit Type Conversion (Automatic): Performed automatically by the compiler.
- Explicit Type Conversion (Manual): Requires the programmer to use casting operators.
Let’s go over these in detail with examples.
1. Implicit Type Conversion (Automatic)
In implicit type conversion, the compiler automatically converts a variable to a compatible type if necessary.
This happens when you mix different data types in an expression. The smaller type is promoted to a larger one to avoid data loss.
Example: Implicit Conversion from int to float
#include <stdio.h> int main() { int num = 10; float result; result = num + 5.5; // 'num' is implicitly converted to float printf("Result: %.2f\n", result); return 0; }
In this example:
- The int variable num is implicitly converted to float to match the data type of 5.5.
- This avoids data loss, allowing the result to be stored in the float variable result.
Example: Implicit Conversion in Mixed-Type Arithmetic
#include <stdio.h> int main() { int a = 5; double b = 3.7; double result; result = a + b; // 'a' is promoted to double printf("Result: %.2f\n", result); return 0; }
In this example:
- a is converted from int to double before addition to match b.
- This allows the result to be accurate and stored in the double variable result.
2. Explicit Type Conversion (Casting)
Explicit type conversion, or casting, is done manually by the programmer.
It’s used when you want to forcefully change the data type, usually with the potential risk of data loss or change in precision.
Syntax for Casting:
(data_type) expression;
Example: Converting float to int
Casting from a floating-point type to an integer type drops the decimal part.
#include <stdio.h> int main() { float num = 7.8; int integerPart; integerPart = (int) num; // Cast 'num' to int printf("Original number: %.2f\n", num); printf("Integer part: %d\n", integerPart); return 0; }
In this example:
- num is a float, and we explicitly cast it to int using (int).
- The result stored in integerPart is 7, as the decimal part .8 is truncated.
Example: Converting double to int in Arithmetic
#include <stdio.h> int main() { double num1 = 7.9, num2 = 2.5; int result; result = (int) num1 + (int) num2; // Both are cast to int before addition printf("Result after casting: %d\n", result); return 0; }
In this example:
- Both num1 and num2 are cast to int before addition, so the fractional parts are discarded.
- The result is 7 + 2 = 9.
3. Type Conversion in Expressions
In C, conversions often happen automatically in mixed-type expressions following certain rules. The types are promoted from lower to higher types in this order:
char → int → float → double
Example: Conversion in Mixed Arithmetic Expressions
#include <stdio.h> int main() { char ch = 'A'; // ASCII value of 'A' is 65 int num = 10; float fnum = 2.5; double result; result = ch + num * fnum; // Conversion hierarchy: char → int → float → double printf("Result: %.2f\n", result); return 0; }
In this example:
- The char ch is promoted to int, then int num is promoted to float, and finally, the result is promoted to double.
- The final output is calculated accurately in double.
4. Using Casting to Control Division Results
In C, dividing two integers results in integer division, which discards any decimal part. To get a floating-point result, you can use casting.
Example: Integer Division with Casting
#include <stdio.h> int main() { int a = 5; int b = 2; float result; result = (float) a / b; // Casting 'a' to float to get floating-point division printf("Result: %.2f\n", result); return 0; }
In this example:
- Casting a to float ensures that division is performed in floating-point, so the result is 2.50 instead of 2.
- Without casting, the result would have been truncated to an integer.
5. Converting Data Types Using Casting in Functions
Casting can be useful in functions that require specific data types as arguments. For instance, using sqrt() requires a double argument.
Example: Using sqrt() with Casting
#include <stdio.h> #include <math.h> int main() { int num = 16; double result; result = sqrt((double) num); // Cast 'num' to double to pass it to sqrt printf("Square root: %.2f\n", result); return 0; }
In this example:
- num is cast to double because sqrt() requires a double argument.
- Casting allows sqrt() to calculate the square root of num.
6. Type Conversion Between Signed and Unsigned
Converting between signed and unsigned types can yield different results, especially when negative values are involved.
Example: Converting Negative int to unsigned int
#include <stdio.h> int main() { int num = -10; unsigned int uNum; uNum = (unsigned int) num; // Casting negative int to unsigned int printf("Signed int: %d\n", num); printf("Unsigned int: %u\n", uNum); return 0; }
In this example:
- Casting num to unsigned int changes its representation in memory, resulting in a large unsigned value.
- This is because unsigned integers interpret the binary representation of -10 differently.
7. Preventing Data Loss with Type Conversion
When converting between larger types to smaller ones (like double to float or int to char), you risk data loss.
Example: Data Loss in Conversion
#include <stdio.h> int main() { double largeNum = 1e12; // Very large double value float fnum; int inum; fnum = (float) largeNum; // Large double to float inum = (int) largeNum; // Large double to int printf("Original double: %.2f\n", largeNum); printf("Converted to float: %.2f\n", fnum); // Precision loss printf("Converted to int: %d\n", inum); // Significant data loss return 0; }
In this example:
- Converting largeNum from double to float loses precision.
- Converting largeNum from double to int results in a significant loss of value, as only the integer part is kept.
8. Summary
Type Conversion | Description | Example |
---|---|---|
Implicit | Automatic conversion by compiler | int to float in a + b |
Explicit | Manually casting using (type) | (float) a / b |
Promotions | Conversion in expressions (hierarchy: int → float → double) | Mixed-type arithmetic |
Preventing Data Loss | Caution when converting large to small types | double to float, int to char |
Complete Example with All Conversions
#include <stdio.h> #include <math.h> int main() { int intVar = 5; float floatVar = 3.5; double doubleVar = 12.6; char charVar = 'A'; // Implicit conversion double implicitResult = intVar + floatVar; // int promoted to float, then to double // Explicit conversion double explicitResult = (double) intVar / 2; // Type promotion in expression float mixedResult = floatVar + doubleVar; // Integer division with explicit conversion float divisionResult = (float) intVar / 3; printf("Implicit Conversion: %.2f\n", implicitResult); printf("Explicit Conversion: %.2f\n", explicitResult); printf("Type Promotion in Mixed Expression: %.2f\n", mixedResult); printf("Controlled Division Result: %.2f\n", divisionResult); return 0; }
This example combines implicit and explicit conversions in various expressions, illustrating how each type behaves and when to use casting in C.
By mastering type conversion, you can ensure your C programs handle data accurately and efficiently.