Arithmetic Operators
The logger stores 21.5 degrees as 215, and the display needs "21" and "5" separately. Two operators do it in one line each, but only if you know exactly how C divides whole numbers, including negative ones.
The rule
Integer division drops the fraction; % keeps what was dropped.
C's arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - |
add, subtract | 215 - 12 |
203 |
* |
multiply | 21 * 10 |
210 |
/ |
divide | 215 / 10 |
21 (both int) |
% |
remainder (integers only) | 215 % 10 |
5 |
The rules that matter:
- Precedence:
*,/and%bind tighter than+and-, and operators of equal rank run left to right.2 + 3 * 4is 14. - Integer division truncates toward zero (guaranteed since C99):
7 / 2is 3 and-7 / 2is -3. %takes the sign of the left operand:-7 % 2is -1. The two always fit together:(a / b) * b + a % b == a.%works only on integer types. For floating-point remainders usefmodfrom<math.h>.- Integer division or remainder by zero is undefined behaviour. Check the divisor first.
The increment and decrement operators add or subtract 1. ++n changes n and gives the new value; n++ changes n but gives the old value:
int n = 5;
int a = n++; /* a is 5, n is 6 */
int b = ++n; /* n is 7, b is 7 */Never modify the same variable twice in one expression without a sequence point between, as in n = n++ + 1; or i++ + i++. That is undefined behaviour, not a puzzle with a right answer.
The shortcut
Split every integer division into quotient and remainder, then check them with the identity quotient * divisor + remainder == original. If the check fails, you have mis-remembered a sign.
Quotient
-37 / 10truncates toward zero: -3.
Drills
Answer fast — trust the rule.
What is 17 / 5?
What is 17 % 5?
What is -17 % 5?
What is 2 + 3 * 4 % 5?
After int n = 5; int m = n++ * 2;, what are m and n?
Remember
- Integer division drops the fraction; % keeps what was dropped, with the sign of the left operand.
- Shortcut: check with
quotient * divisor + remainder == original. - Trap: dividing by zero, or changing one variable twice in one expression, is undefined behaviour.
