Skip to content
AgileLogics
4 min read

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 / b behaves like calculator division when both are int — cast at least one operand to double before the division, not after.