Lesson 13: Type Casting and Conversion Rules
Mixing different data types in an expression can lead to either implicit or explicit type conversion (casting).
Implicit Conversion (Coercion)
Done automatically by the compiler to prevent loss of data or precision. This happens when promoting a lower rank type to a higher rank type (e.g., int to float).
Promotion Hierarchy (simplified): char < int < long < float < double
c int a = 10; double b = 3.5; double result = a + b; // 'a' (10) is implicitly promoted to double (10.0)
Explicit Conversion (Type Casting)
When you need to force a conversion, especially to convert a higher rank type to a lower rank type (which may involve data loss).
Syntax: (target_data_type) expression
Example: Fixing Integer Division
c int num1 = 10; int num2 = 3;
// Problem: Integer division results in 3 float avg1 = num1 / num2; // avg1 is 3.0
// Solution: Explicitly cast one operand to float float avg2 = (float)num1 / num2; // avg2 is 3.333...
Casting Pointers (Preview)
Casting is also essential when working with memory allocation functions like malloc, although modern C standards often make this optional.