C - Type Casting

Type casting converts a value from one type to another. Use explicit casts to clarify intent.

Learning Objectives

  • Use explicit casts to control conversions.
  • Avoid undefined behavior from invalid casts.

Examples

double d = 3.7;
int i = (int)d;       // 3 (truncation)
int a = 5, b = 2;
double q = (double)a / b; // 2.5

Common Pitfalls

  • Casting pointers to incompatible types and dereferencing.
  • Relying on implicit conversions that change meaning.