Mixing int and float in arithmetic
What you'll learn: How C automatically handles calculations when you combine whole numbers and decimals.
The "Promotion" Rule
In C, when you perform arithmetic between an integer (int) and a floating-point number (float or double), the computer doesn't get confused. Instead, it follows a rule called Type Promotion.
Think of it like a professional sports league: if a minor league team plays against a major league team, the game is played by major league rules. In C, the float is the major league type because it is more precise—it can handle everything an integer can, plus decimals. Therefore, if you add an int to a float, C temporarily "promotes" the int to a float before doing the math. The result of the calculation will always be a float.
Watching it in action
If you divide 10 (an int) by 4.0 (a float), C sees the decimal and decides the whole operation must be high-precision. It treats the calculation as 10.0 / 4.0, resulting in 2.5.
However, if you perform math between two integers first, C stays in "integer mode" and chops off any remainder. This is a common trap! Look at how the placement of a decimal changes the outcome:
#include <stdio.h>
int main() {
int apples = 5;
float price = 1.5;
// An int times a float results in a float
float total = apples * price; // 5 * 1.5 = 7.5
// Beware of integer division!
float result1 = 5 / 2; // Both are ints. Result is 2 (integer math).
float result2 = 5 / 2.0; // One is a float. Result is 2.5 (float math).
printf("Total: %.1f\n", total);
printf("Result 1: %.1f\n", result1);
printf("Result 2: %.1f\n", result2);
return 0;
}
Why it matters
This automatic promotion helps prevent data loss. If C forced a float into an int, you would lose all the information after the decimal point. By upgrading the int to a float, C ensures the answer is as accurate as possible. Just remember: if you want a precise decimal answer, at least one number in your expression must be a float.
Key takeaway
When an int meets a float, the int is promoted to a float and the result is always a float.