Type Casting & Conversion
Prerequisites: Variables & data types
Converting between numeric types can happen automatically or via an explicit cast:
int whole = 42;
double asDouble = whole; // automatic, safe (widening)
double price = 19.99;
int asInt = (int) price; // explicit cast (narrowing)
printf("%d\n", asInt); // 19 — truncated, not rounded
A classic C gotcha: dividing two ints always produces an int,
even when assigned to a double:
int a = 7, b = 2;
double result = a / b; // 3.0 — integer division happened FIRST
double correct = (double) a / b; // 3.5 — cast before dividing
Common mistakes
- Assuming
a / bbehaves like calculator division when both areint— cast at least one operand todoublebefore the division, not after.