Type conversion & casting
8 min lesson
- Type conversion is the process of changing a value from one data type to another, like turning an int into a double or a double into an int.
- Conversion matters because real calculations often mix types, and C needs clear rules for what happens when types meet.
- Think of conversion as pouring liquid between containers of different sizes: a small cup into a big jug is safe, but a big jug into a small cup can spill (lose data).
- Implicit conversion happens automatically when the compiler sees mixed types, usually widening smaller types to larger ones: int to double is safe.
- Explicit conversion, called casting, is when you write the target type in parentheses: (double)count. It tells the compiler you meant to convert.
- Narrowing conversion goes from a larger or more precise type to a smaller one: double to int, or long to short. It can lose information and should be done with care.
- The computer follows a set of promotion rules, converting operands to a common type before doing arithmetic, then storing the result in the destination type.
- The syntax is: (targetType)value; for example (int)3.99 gives 3, and (double)7 / 2 gives 3.5.
- A realistic use: computing an average of integer scores by casting the sum to double before dividing.
- A surprising detail: casting a double to int truncates toward zero, it does not round; 3.99 becomes 3 and -3.99 becomes -3.
- The example program computes an integer average and a precise double average of the same scores, then shows truncation.
- Cast when you want to be explicit about converting between types.
- Watch out for narrowing conversions; they silently lose data like decimals or large values.
- Cast before dividing if you need a decimal result: (double)sum / count.
- Remember that casting a negative double to int truncates toward zero, not down.
- You now understand how C handles mixed types. This is a big step forward!
#include <stdio.h>
int main(void) {
// Three whole-number scores
int score1 = 80;
int score2 = 90;
int score3 = 75;
int count = 3;
// Integer sum and integer average (drops the decimal part)
int sum = score1 + score2 + score3;
int intAverage = sum / count;
// Print the integer average
printf("Integer average: %d\n", intAverage);
// Cast the sum to double so the division keeps the decimal part
double preciseAverage = (double)sum / count;
// Print with two decimal places
printf("Precise average: %.2f\n", preciseAverage);
// Casting a double to int truncates toward zero
double price = 9.99;
int truncated = (int)price;
// Print the truncated value to show the decimal is lost
printf("Truncated price: %d\n", truncated);
return 0;
}What happens: Integer average: 81 Precise average: 81.67 Truncated price: 9
Breaking it down
Integer sum
int sum = score1 + score2 + score3;Adds three int values and stores the total in an int. Because all values are int, the whole operation stays in integers.
Integer division
sum / countBoth sum and count are int, so the division gives an int. The decimal part is thrown away, giving 81 instead of 81.67.
Cast to double
(double)sum / countConverts sum to double first. Then double divided by int promotes count to double too, so the division keeps the decimals.
Storing in double
double preciseAverage = ...;The precise result fits in a double and keeps the two decimal places. Printing with %.2f shows 81.67.
Narrowing cast
(int)priceConverts the double 9.99 to int, which truncates to 9. The .99 is lost, not rounded. This is why narrowing must be intentional.
Common conversions in C
| From | To | Result | Data loss? |
|---|---|---|---|
| int 7 | double | 7.0 | No |
| float 3.5f | double | 3.5 | No |
| double 3.99 | int | 3 | Yes, decimal lost |
| double -3.99 | int | -3 | Yes, truncates toward zero |
| long 1000000 | short | May wrap | Yes, large value lost |
| char 'A' | int | 65 | No |
A helpful analogy
Type conversion is like pouring water between containers. Pouring a small cup (int) into a big jug (double) is safe because nothing is lost. Pouring a big jug into a small cup (double into int) spills some water, and the spilled water is gone for good, just like the decimal part.
Nesting rules
- 1.Cast before arithmetic when you need a specific result type: (double)a / b, not (double)(a / b).
- 2.Narrowing conversions (double to int) truncate toward zero; they do not round to the nearest value.
- 3.Implicit conversion follows promotion rules; smaller types are promoted to larger ones in mixed expressions.
- 4.Assigning a double to an int is an implicit narrowing conversion; prefer an explicit cast to show you meant it.
Common mistakes
Casting after the division
Avoid
double avg = (double)(a / b); // still integerUse instead
double avg = (double)a / b; // decimal keptThe division happens first in integer arithmetic, losing the decimal before the cast. Cast one operand before dividing.
Expecting casting to round
Avoid
int n = (int)9.99; // gives 9, not 10Use instead
int n = (int)(9.99 + 0.5); // manual roundingCasting a double to int truncates toward zero. If you need rounding, add 0.5 before casting for positive numbers.
Ignoring the warnings for implicit narrowing
Avoid
int x = 3.14; // loses .14 silentlyUse instead
int x = (int)3.14; // explicitImplicit narrowing compiles but silently loses data. The explicit cast shows readers you intended the conversion.
Quick tips
- •Use casts to make your intent clear, not to silence warnings you do not understand.
- •Prefer int-to-double widening; it is always safe and does not lose data.
- •When averaging, cast the sum to double before dividing by the count.
- •Try printing (int)3.9 and (int)-3.9 to see truncation toward zero.
- •Check compiler warnings about conversion; they often point to real bugs.