Type Conversion in C

Type conversion in C is the process of converting one data type into another. This is also called typecasting. It allows operations between different data types and ensures compatibility.

Types of Type Conversion

  • Implicit Type Conversion (Type Promotion): The compiler automatically converts a smaller or lower type to a larger or higher type.
  • Explicit Type Conversion (Type Casting): The programmer manually converts a value from one type to another using a cast operator.

Implicit Type Conversion (Type Promotion)

Occurs automatically when a value is assigned to a variable of a different type or used in an expression with mixed types.

Example: int a = 5; float b = a; // int converted to float automatically

Explicit Type Conversion (Type Casting)

The programmer explicitly converts a value to a different type using parentheses and the target type.

Example: int a = 10; float b = (float)a; // int explicitly converted to float

Key Points

  • Used to avoid type mismatch errors
  • Helps in operations with mixed data types
  • Implicit conversion happens automatically, explicit conversion requires typecasting
  • Be careful with conversions that can lose data (e.g., float to int)

Common Mistakes

  • Assuming implicit conversion always preserves accuracy
  • Casting incorrectly and losing fractional part in float-to-int conversion
  • Using type conversion unnecessarily, making code confusing
  • Confusing type promotion rules in expressions with multiple data types