The Analogy: A Calculator With Very Strict Boxes
A pocket calculator will happily tell you that 7 divided by 2 is 3.5. C tells you it is 3.
C is not being careless. It is doing precisely what you asked. When both operands of a division are whole numbers, C stays inside the world of whole numbers and discards the fractional part. The types of the operands decide the arithmetic, not the values.
Picture every C variable as a labelled box of a fixed size. Arithmetic is the act of taking numbers out of boxes, doing the maths, and pushing the result back into a box. If the result does not fit the shape of the box — a fraction heading into an int, or a huge number heading into a char — something is lost on the way in, and C will not stop to warn you.
That sounds like a trap, and sometimes it is. But integer division is also one of C's sharpest tools: it is exactly what you want when you are splitting items into pages, converting seconds into hours, or laying values out in a grid. Once you know which world an expression lives in, the results stop being surprising.
Syntax or Core Structure
C gives you five basic arithmetic operators. Four of them behave the way school taught you; the fifth, %, gives you what is left over.
#include <stdio.h>
int main(void) {
int a = 17, b = 5;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b); /* integer division: truncates */
printf("a %% b = %d\n", a % b); /* remainder */
double x = 17.0, y = 5.0;
printf("x / y = %.4f\n", x / y); /* floating division: keeps the fraction */
return 0;
}
Output:
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
x / y = 3.4000
Assignment and Compound Assignment
= is an operator, not a statement, and it produces a value. Every arithmetic operator has a compound form that reads and writes the same variable in one step.
| Written long-hand | Compound form | Meaning |
|---|---|---|
total = total + 8; | total += 8; | add and store |
total = total - 8; | total -= 8; | subtract and store |
total = total * 2; | total *= 2; | multiply and store |
total = total / 2; | total /= 2; | divide and store |
total = total % 7; | total %= 7; | keep the remainder |
Compound forms are not just shorter — they evaluate the left-hand side only once, which matters when that side is something like grid[next_index()].
Increment and Decrement
++ and -- add or subtract one. Where you put them changes what the expression hands back, though the variable ends up the same either way.
#include <stdio.h>
int main(void) {
int i = 5;
printf("i++ gives %d, ", i++); /* hands back 5, then i becomes 6 */
printf("i is now %d\n", i);
printf("++i gives %d, ", ++i); /* i becomes 7, then hands back 7 */
printf("i is now %d\n", i);
return 0;
}
Output:
i++ gives 5, i is now 6
++i gives 7, i is now 7
As a standalone statement, i++; and ++i; are identical, so prefer whichever your project uses consistently. Inside a larger expression the difference is real, and that is exactly where it becomes hard to read.
Precedence, Briefly
*, / and % all bind tighter than + and -, and assignment binds loosest of all.
| Binds tightest to loosest | Operators | Associativity |
|---|---|---|
| 1 | postfix ++ -- | left to right |
| 2 | prefix ++ --, unary + -, casts | right to left |
| 3 | * / % | left to right |
| 4 | + - | left to right |
| 5 | = += -= *= /= %= | right to left |
So 2 + 3 * 4 is 14, and total = base + rate * hours multiplies before it adds. When in doubt, add parentheses: they cost nothing at run time and they cost the next reader nothing either.
Technical Depth: Truncation, Remainders and Overflow
The type of an expression is decided before any value is computed
This is the single most important rule in C arithmetic. The compiler looks at the operand types, works out the result type, and only then does the machine compute a value.
| Expression | Result type | Value | Why |
|---|---|---|---|
7 / 2 | int | 3 | both operands are int, so the fraction is discarded |
7 / 2.0 | double | 3.5 | 2.0 is a double, so 7 is converted to 7.0 first |
-7 / 2 | int | -3 | C truncates toward zero, not toward minus infinity |
-7 % 2 | int | -1 | the sign of a remainder follows the left operand |
7 % -2 | int | 1 | again, the left operand sets the sign |
(double)7 / 2 | double | 3.5 | the cast applies before the division |
(double)(7 / 2) | double | 3.0 | too late — the truncation already happened |
For any integers a and b where b is not zero, C guarantees the identity (a / b) * b + a % b == a. That identity is why the signs of / and % have to agree.
Overflow: one case is defined, the other is not
Unsigned types wrap around cleanly and predictably — the standard says they behave modulo two to the power of their bit width. Signed types do not: signed overflow is undefined behaviour, which means the compiler is allowed to assume it never happens and optimise on that assumption.
#include <stdio.h>
#include <limits.h>
int main(void) {
unsigned char u = 250;
u += 10; /* 260 does not fit: wraps to 260 - 256 */
printf("unsigned char 250 + 10 = %u\n", u);
int big = INT_MAX;
printf("INT_MAX = %d\n", big);
/* big + 1 would be undefined behaviour, so test BEFORE adding */
if (big > INT_MAX - 1) {
printf("adding 1 would overflow, so we refuse\n");
}
return 0;
}
Output:
unsigned char 250 + 10 = 4
INT_MAX = 2147483647
adding 1 would overflow, so we refuse
Note the shape of the safety check: big > INT_MAX - 1 rather than big + 1 > INT_MAX. The second version has to overflow in order to test for overflow, so it is worthless. Always rearrange the check so the dangerous operation never executes.
Two more rules worth memorising
- Division or remainder by zero is undefined behaviour, not an exception. There is nothing to catch. Test the divisor yourself before you use it.
%does not accept floating-point operands — it is a compile error, not a silent conversion. For a floating remainder, include<math.h>and callfmod(x, y).
Real World Example: Turning a Duration Into a Readable Clock
Every log viewer, media player and build tool has to do this: take one number of seconds and split it into days, hours, minutes and seconds. It is the cleanest demonstration that integer division and % are partners — / tells you how many whole units fit, and % hands you the leftover to keep working on.
#include <stdio.h>
int main(void) {
long total = 100000; /* seconds elapsed */
long days = total / 86400; /* 86400 seconds in a day */
long hours = (total % 86400) / 3600; /* leftover, then to hours */
long minutes = (total % 3600) / 60;
long seconds = total % 60;
printf("%ld seconds = %ldd %02ldh %02ldm %02lds\n",
total, days, hours, minutes, seconds);
return 0;
}
Output:
100000 seconds = 1d 03h 46m 40s
Two details are doing the real work. The %02ld width flag pads with a leading zero so the columns line up in a log file. And each line takes its remainder from the next larger unit, not from the original total — (total % 3600) / 60 gives minutes-within-the-hour, whereas total / 60 would give the grand total of minutes.
The same pattern converts a record index into a page number and a row on that page:
int index = 47, per_page = 10;
int page = index / per_page; /* 4 */
int row = index % per_page; /* 7 */
If you ever find yourself writing floor() on two integers, stop: / already did it.
Common Mistakes
- Expecting a fraction from two integers.
double avg = sum / count;computes an integer average and only then widens it. Cast one operand:(double)sum / count. - Casting the result instead of an operand.
(double)(7 / 2)is 3.0. The cast cannot recover digits that were already thrown away. - Averaging two large values with
(a + b) / 2. The sum can overflow before the division ever runs. Writea + (b - a) / 2instead. - Using
%or/without checking the divisor. Zero is not an exception in C; it is undefined behaviour, and on most machines it is a hard crash. - Assuming
-7 % 2is1. That is Python's rule. C's remainder takes the sign of the left operand, so the answer is-1. Code ported from a scripting language breaks here silently. - Using a variable twice in one expression when
++touches it.arr[i++] = i;is undefined behaviour — the standard does not say which side happens first. - Mixing signed and unsigned. In
if (count - 1 < total)withunsigned count = 0, the subtraction wraps to a colossal positive number and the test goes the wrong way. - Writing
=where==was meant.if (x = 0)assigns and is always false. Some compilers warn; do not rely on it.
Best Practices
- Parenthesise any expression that mixes
*,/,%with+and-. Precedence is not the reader's job to recall. - For floating division, cast one operand, at the point of use:
(double)hits / attempts. - Guard every divisor with an explicit check before the division, and decide what the zero case should return.
- Prefer compound assignment (
total += n) so the left-hand side is written and evaluated once. - Keep
++and--on a line of their own. Their value-versus-side-effect distinction is a bug factory inside larger expressions. - Reach for unsigned types only when negative values are genuinely impossible and wrap-around is acceptable. Never compare a signed value against an unsigned one.
- Rearrange overflow checks so the risky operation never executes: test
a > INT_MAX - bbefore computinga + b. - Build with
-Wall -Wextra -Wconversionand run your tests once under-fsanitize=undefined. It catches overflow and divide-by-zero the moment they occur.
Practice Exercises
- Change machine. Read an amount in cents and print how many dollars, quarters, dimes, nickels and pennies make it up, using only
/and%. Verify that 287 cents gives 2 dollars, 3 quarters, 1 dime, 0 nickels, 2 pennies. - Two kinds of average. Read five integers. Print both the truncated integer average and the true average to two decimal places, then write a one-line comment explaining exactly which cast makes the second version correct.
- Safe divide. Write a program that reads two integers, refuses to continue if the second is zero, and otherwise prints the quotient, the remainder and the floating-point quotient. Confirm on paper that
(a / b) * b + a % breproducesafor the pairs(17, 5),(-17, 5)and(17, -5).