Arithmetic Operators
C's arithmetic operators follow normal precedence, integer division truncates toward zero, and % gives the remainder with the sign of the left operand.
Predict division and remainder from operand types before formatting the result.
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.