C Type Casting

Type casting converts a value from one data type to another.

1. Implicit Casting

int i = 10;
float f = i;  // int to float (automatic)

2. Explicit Casting

float f = 3.14;
int i = (int)f;  // float to int (explicit)

3. Pointer Casting

void *ptr = malloc(100);
int *int_ptr = (int*)ptr;

4. Common Casts

double d = 3.99;
int i = (int)d;  // i = 3 (truncation)

char c = 'A';
int ascii = (int)c;  // ascii = 65

5. Safety Considerations

  • Be careful with pointer casting
  • Check for data loss when casting to smaller types
  • Use proper casting for function pointers