Common conversion pitfalls
What you'll learn: How to avoid data loss and "silent" bugs when C automatically changes one variable type into another.
The "Size" Problem
C is very helpful—sometimes too helpful. When you perform math with different types, like adding an int to a float, C automatically converts them so the math works. This is called implicit conversion.
Think of variables like storage containers. An int (integer) is like a small box for whole numbers, while a double (floating-point) is a much larger, more complex crate that can hold decimals. If you try to pour the contents of a large double crate into a small int box, the "overflow" simply disappears. C won't stop you; it will just chop off the decimal part without warning.
Losing Information
The most common pitfall happens during assignment or division. If you assign 3.99 to an integer variable, the computer doesn't round up to 4. It performs "truncation," effectively grabbing a pair of scissors and snipping off everything after the decimal point. You are left with 3, and that 0.99 is gone forever.
Another trap is integer division. If you divide two integers, C assumes the result must be an integer. Even if you save the result into a float, the damage is done before the saving happens.
#include <stdio.h>
int main() {
int bankBalance = 100;
int items = 3;
// Pitfall 1: Integer division happens BEFORE the conversion
// 100 / 3 is 33.333, but since both are ints, C makes it 33.
float averagePrice = bankBalance / items;
// Pitfall 2: Narrowing conversion
// The decimal is sliced off entirely.
int roundedPrice = 39.95;
printf("Average: %f\n", averagePrice); // Prints 33.000000, not 33.333
printf("Rounded: %d\n", roundedPrice); // Prints 39
return 0;
}
Why This Matters
These bugs are dangerous because your code will compile and run without errors. However, your calculations—like physics in a game or interest in a banking app—will be slightly off. Over thousands of calculations, these tiny "snips" add up to massive errors. Always ensure the variable receiving the data is "large" enough to hold the precision you expect.
Key takeaway
Implicit conversion truncates decimals when moving from floating-point to integers, leading to silent data loss.