Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Arithmetic Operators in Embedded C: Relational, Logical and Short-Circuit Evaluation
Everything about + – * / %, the integer division trap, overflow and promotion, relational and logical operators, short-circuit evaluation and a practical precedence table, with compiled examples. Keep this in mind whenever you use arithmetic operators in embedded C.
What You Will Learn
+ - * / % and their exact integer behavior&& || ! and short-circuit evaluationKey Terms
1. Operators, Operands and Expressions
An operator is a symbol that tells the compiler to perform a computation. The values it works on are operands, and the combination is an expression that produces a value. In total = a + b * 2; the symbols =, + and * are operators, and total, a, b, 2 are operands. Operators are the verbs of C: every register update on a microcontroller, every sensor conversion and every decision is built from them. Many firmware bugs with arithmetic operators in embedded C start here.
Operators are grouped by how many operands they take and by what they do. This module walks through all of them; Lesson 5.1 covers the three groups that appear in nearly every line of firmware, the arithmetic operators in embedded C, the relational operators and the logical operators. This is the core rule behind arithmetic operators in embedded C.
| Group | Operators | Result | Covered in |
|---|---|---|---|
| Arithmetic | + - * / % | a number | This lesson |
| Relational | == != < > <= >= | 0 or 1 (an int) | This lesson |
| Logical | && || ! | 0 or 1 | This lesson |
| Bitwise | & | ^ ~ << >> | a number | Lessons 5.2 and 5.3 |
| Assignment, ++/–, ?: | = += ++ ?: | the assigned value | Lesson 5.4 |
2. Arithmetic Operators
C provides five binary arithmetic operators and the unary plus and minus. For integers they behave exactly as described below, and these rules matter much more in firmware than on a PC because the data sizes are small and the hardware has no safety net. Reviewers check arithmetic operators in embedded C first.
| Operator | Name | Example | Result | Notes |
|---|---|---|---|---|
+ | addition | 7 + 3 | 10 | |
- | subtraction | 7 - 3 | 4 | Also unary minus: -x |
* | multiplication | 7 * 3 | 21 | Watch for overflow |
/ | division | 7 / 3 | 2 | Integers: fraction discarded |
% | remainder (modulo) | 7 % 3 | 1 | Integers only |
Integer division truncates toward zero
When both operands are integers, / produces an integer: the fractional part is thrown away (not rounded). Since C99 the result is always truncated toward zero, so -7 / 2 is -3, not -4. The remainder operator is defined so that (a / b) * b + (a % b) == a always holds; therefore the remainder takes the sign of the dividend. Interviewers test arithmetic operators in embedded C on exactly this point.
17 / 5 = 3 2 left over → 17 % 5 = 2(head + 1) % SIZE), splitting seconds into minutes and seconds (t / 60 and t % 60), converting a number to decimal digits (n % 10 then n / 10) and checking even/odd (n % 2).3. The Integer Division Trap
The most common arithmetic bug in beginner firmware is expecting a fractional answer from integer operands. The decision is made by the types of the two operands, not by where you store the result.
The rule: convert before you divide. Converting the result is too late because the fraction is already gone. On the STM32F407 the Cortex-M4F has a hardware single-precision FPU, so float division is fast, but many smaller Cortex-M0 parts have none, and for them it is better to avoid floating point and scale integers instead:
- Multiply first, divide last to keep as many significant digits as possible.
- Make sure the intermediate product fits:
3000 * 3300 = 9,900,000fits easily in a 32-bituint32_t, but it would overflow a 16-bit type. - Use unsigned constants (
3300u) so the arithmetic is unsigned, avoiding signed-overflow surprises.
SDIV instruction returns 0 by default (it traps only if the DIV_0_TRP bit is set), but you cannot rely on this on other parts. Always check a divisor that comes from data.4. Overflow, Promotion and Mixed Types
Arithmetic on small types happens in int. This is the integer promotion rule you met in Lesson 3.3: operands narrower than int are promoted before the operation. On the 32-bit Cortex-M4 int is 4 bytes, which is convenient, but the stored result is converted back and can silently wrap:
| Situation | Behavior | Defined by the C standard? |
|---|---|---|
| Unsigned arithmetic exceeds the type | Wraps around modulo 2N | Yes |
| Signed arithmetic exceeds the type | Anything: wrap, trap, or optimized away | No (undefined behavior) |
| Result stored in a narrower type | Converted: high bits lost | Yes (implementation-defined for signed) |
| Division by zero | Unpredictable | No |
For this reason many embedded teams use unsigned types for counters, timers and registers, and compile with -fwrapv or avoid relying on signed overflow. Lesson 3.3 explains the usual arithmetic conversions between operands of different types in detail.
5. Relational Operators
Relational operators compare two values and produce 1 if the relation holds and 0 if it does not. The result is an int, not a special boolean type (although C99 adds _Bool and <stdbool.h> for variables).
| Operator | Meaning | Example | Value |
|---|---|---|---|
== | equal to | 5 == 5 | 1 |
!= | not equal to | 5 != 5 | 0 |
< | less than | 3 < 5 | 1 |
> | greater than | 3 > 5 | 0 |
<= | less than or equal | 5 <= 5 | 1 |
>= | greater than or equal | 3 >= 5 | 0 |
Three classic traps
if (state = 1) assigns 1 to state and is always true. Compile with -Wall (GCC warns about assignments used as conditions) and, in some styles, write the constant first: if (1 == state).0 < x < 10 does not test a range. It evaluates (0 < x) to 0 or 1 and then compares that with 10, which is always true. Write (x > 0) && (x < 10).0.1 + 0.2 == 0.3 is false because of rounding. Compare with a tolerance: fabsf(a - b) < 1e-6f.Signed and unsigned values mixed in a comparison are converted to unsigned, which makes -1 < 0u false. Lesson 3.3 showed this trap; with -Wextra (which includes -Wsign-compare) GCC warns about it.
6. Logical Operators
Logical operators combine truth values. In C, any non-zero value is true and zero is false, and a logical operator always yields exactly 0 or 1.
| A | B | A && B (AND) | A || B (OR) | !A (NOT) |
|---|---|---|---|---|
| 0 (false) | 0 (false) | 0 | 0 | 1 |
| 0 (false) | non-zero | 0 | 1 | 1 |
| non-zero | 0 (false) | 0 | 1 | 0 |
| non-zero | non-zero | 1 | 1 | 0 |
5 && 2 is 1 (both non-zero) but 5 & 2 is 0 (no common bits). Mixing them up is a frequent register-handling bug; Lesson 5.2 covers the bitwise operators.7. Short-Circuit Evaluation
&& and || evaluate their left operand first and stop as soon as the result is known. If the left side of && is false, the right side is never evaluated; if the left side of || is true, the right side is skipped. The C standard guarantees this order (there is a sequence point after the left operand).
Why short-circuiting matters in embedded code
- Safe pointer access:
if (p != NULL && p->ready)never dereferences a null pointer. - Safe array indexing:
if (i < N && buf[i] == 0)checks the index before reading. - Avoiding division by zero:
if (n != 0 && total / n > 10). - Saving time: put the cheap test first:
if (flag && expensive_check()). - Side-effect traps:
if (a && (b = read_sensor()))reads the sensor only whenais true. Keep such side effects out of conditions.
p != NULL && p->ready to p->ready && p != NULL removes the protection. Always place the guard on the left.8. Operator Precedence and Associativity (Overview)
When an expression has several operators, precedence decides which is applied first, and associativity breaks ties between operators of the same level. This table lists the groups from this module, from highest to lowest:
| Level | Operators | Associativity | Example |
|---|---|---|---|
| 1 | () [] . -> postfix ++ -- | left to right | a[i]++ |
| 2 | prefix ++ --, unary + - ! ~ * &, sizeof, casts | right to left | -x, !flag |
| 3 | * / % | left to right | a * b % c |
| 4 | + - | left to right | a + b - c |
| 5 | << >> | left to right | 1 << n |
| 6 | < <= > >= | left to right | a < b |
| 7 | == != | left to right | a == b |
| 8 | & | left to right | a & m |
| 9 | ^ | left to right | |
| 10 | | | left to right | |
| 11 | && | left to right | a && b |
| 12 | || | left to right | a || b |
| 13 | ?: | right to left | c ? x : y |
| 14 | = += -= *= /= %= &= ^= |= <<= >>= | right to left | a = b = 0 |
| 15 | , | left to right | i++, j-- |
9. Common Mistakes With Basic Operators
average = sum / count; with integers truncates. Scale (sum * 100 / count) or convert before dividing.x / 4095 * 3300 yields 0 for any x below 4095. Multiply first.0 < x < 10: Always true. Use &&.INT_MAX + 1 is undefined behavior; the optimizer may remove checks that assume it cannot happen.-7 % 3 is -1, so an array index computed as x % N can be negative.10. Best Practices for Arithmetic Operators in Embedded C
- Use fixed-width unsigned types for counters and hardware values; convert explicitly when mixing signs.
- Multiply first, divide last, and check that the intermediate product cannot overflow the type.
- Put guards on the left of
&&; keep side effects out of conditions. - Always parenthesise mixed arithmetic, bitwise and comparison operators.
- Treat any comparison of floating-point values for equality as a bug unless you have proved otherwise.
- Check divisors that come from inputs before dividing.
- Compile with
-Wall -Wextra, plus-Wconversionin code that does a lot of arithmetic on narrow types. - Prefer shifts and masks only when you need bits; use
*and/for arithmetic and let the compiler optimize.
Key Takeaways — Lesson 5.1
- The arithmetic operators in embedded C are
+ - * / %; integer division truncates toward zero and the remainder takes the sign of the dividend. - Convert to a wider type before dividing; multiply first, divide last.
- Unsigned overflow wraps (defined); signed overflow is undefined behavior.
- Relational operators return 1 or 0 as an
int;0 < x < 10is not a range test. - Logical operators treat any non-zero as true and return exactly 0 or 1;
&&differs from&. &&and||short-circuit: the right side may never run.- Precedence: unary,
* / %,+ -, shifts, relational, equality, bitwise,&&,||,?:, assignment. When unsure, use parentheses.
Frequently Asked Questions
Ready to practise?
Next: operators with output prediction, the integer division trap, short-circuit demos and a precedence workout.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments