Loading lessons...
Type Conversion (Casting)
Type Conversion (Casting)
Values often need to move between types - an int into a double, a double into an int. That movement is called type conversion.
Implicit conversion
Sometimes C converts types for you, automatically:
int a = 5;
double b = a; // 5 -> 5.0, no complaint
The narrowing trap
Going the other way can silently lose data:
double pi = 3.99;
int x = pi; // x becomes 3, the .99 silently disappears
This is narrowing: data is quietly lost.
The integer division trap
Dividing two ints does integer division - the fractional part is thrown away:
int a = 7;
int b = 2;
printf("%d", a / b); // 3, not 3.5!
Explicit conversion: casting
To convert on purpose, write the target type in parentheses before the value:
int a = 7;
int b = 2;
double result = (double)a / b; // 3.5
TL;DR
- Implicit conversion happens automatically (int to double is safe).
- Narrowing quietly loses data (double to int drops the fraction).
- Integer division:
7 / 2is3, not3.5. - Use a cast to convert on purpose:
(double)a / b.