Arithmetic Operators in Embedded C: Relational, Logical and Short-Circuit Evaluation-Free Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

MODULE 5 · LESSON 5.1 · THEORY

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.

55 min
Read Time
Beginner
Level
M5 · L1
Module / Lesson

What You Will Learn

✓ Operators, operands and expressions; unary, binary and ternary forms
✓ Arithmetic operators + - * / % and their exact integer behavior
✓ The integer division trap and how to scale correctly
✓ Relational operators and why they return 0 or 1
✓ Logical operators && || ! and short-circuit evaluation
✓ Precedence and associativity: a practical overview
✓ Overflow and promotion rules that matter on a 32-bit Cortex-M4
✓ Common mistakes and best practices

Key Terms

OperatorOperandExpressionInteger divisionModuloTruncationRelationalLogicalShort-circuitPrecedenceAssociativityInteger promotionOverflowTruth value

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.

Operators by number of operands
Unary (1 operand)
-x   !flag   ~m   x++
sign, logical not, bitwise not, increment, address-of, sizeof
Binary (2 operands)
a + b   x < y   p && q
arithmetic, relational, logical, bitwise, assignment
Ternary (3 operands)
c ? a : b
the only one: conditional operator (Lesson 5.4)
GroupOperatorsResultCovered in
Arithmetic+ - * / %a numberThis lesson
Relational== != < > <= >=0 or 1 (an int)This lesson
Logical&& || !0 or 1This lesson
Bitwise& | ^ ~ << >>a numberLessons 5.2 and 5.3
Assignment, ++/–, ?:= += ++ ?:the assigned valueLesson 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.

OperatorNameExampleResultNotes
+addition7 + 310
-subtraction7 - 34Also unary minus: -x
*multiplication7 * 321Watch for overflow
/division7 / 32Integers: fraction discarded
%remainder (modulo)7 % 31Integers only
arith_basics.c
#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 (integer division: 3.4 becomes 3)\n”, a / b); printf(“a %% b = %d (the remainder: 17 = 3*5 + 2)\n”, a % b); printf(“\nCheck: (a / b) * b + (a %% b) = %d\n”, (a / b) * b + (a % b)); return 0; }
Output (verified by compiling and running)
a + b = 22 a – b = 12 a * b = 85 a / b = 3 (integer division: 3.4 becomes 3) a % b = 2 (the remainder: 17 = 3*5 + 2) Check: (a / b) * b + (a % b) = 17

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.

div_signs.c
#include <stdio.h> int main(void) { printf(” 7 / 2 = %d 7 %% 2 = %d\n”, 7 / 2, 7 % 2); printf(“-7 / 2 = %d -7 %% 2 = %d\n”, –7 / 2, –7 % 2); printf(” 7 / -2 = %d 7 %% -2 = %d\n”, 7 / –2, 7 % –2); printf(“-7 / -2 = %d -7 %% -2 = %d\n”, –7 / –2, –7 % –2); return 0; }
Output (verified by compiling and running)
7 / 2 = 3 7 % 2 = 1 -7 / 2 = -3 -7 % 2 = -1 7 / -2 = -3 7 % -2 = 1 -7 / -2 = 3 -7 % -2 = -1
How 17 / 5 and 17 % 5 split the number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
3 full groups of 5 → 17 / 5 = 3 2 left over → 17 % 5 = 2
Where % shows up in firmware: Wrapping a ring-buffer index ((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.

division_trap.c
#include <stdio.h> int main(void) { int total = 7, count = 2; float wrong = total / count; /* int / int = 3, THEN converted to 3.0 */ float right1 = (float)total / count; /* float / int -> float division */ float right2 = total / 2.0f; /* int / float -> float division */ float late = (float)(total / count); /* cast too late: still 3.0 */ printf(“wrong = %.2f\n”, wrong); printf(“right1 = %.2f\n”, right1); printf(“right2 = %.2f\n”, right2); printf(“late = %.2f\n”, late); return 0; }
Output (verified by compiling and running)
wrong = 3.00 right1 = 3.50 right2 = 3.50 late = 3.00

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:

scaling.c
#include <stdio.h> #include <stdint.h> int main(void) { uint32_t adc = 3000; /* 12-bit ADC reading, 0..4095 */ uint32_t mv_bad = adc * (3300 / 4095); /* 3300/4095 = 0 in integers! */ uint32_t mv_good = (adc * 3300u) / 4095u; /* multiply first, divide last */ printf(“bad : %u mV\n”, (unsigned)mv_bad); printf(“good : %u mV\n”, (unsigned)mv_good); printf(“float: %.1f mV\n”, adc * 3.3 * 1000.0 / 4095.0); return 0; }
Output (verified by compiling and running)
bad : 0 mV good : 2417 mV float: 2417.6 mV
  • Multiply first, divide last to keep as many significant digits as possible.
  • Make sure the intermediate product fits: 3000 * 3300 = 9,900,000 fits easily in a 32-bit uint32_t, but it would overflow a 16-bit type.
  • Use unsigned constants (3300u) so the arithmetic is unsigned, avoiding signed-overflow surprises.
Division by zero: Integer division by zero is undefined behavior in C. On a Cortex-M4 the 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:

promotion_overflow.c
#include <stdio.h> #include <stdint.h> int main(void) { uint8_t a = 200, b = 100; uint8_t sum8 = a + b; /* computed as int 300, stored mod 256 */ int sum = a + b; /* no loss: the int can hold 300 */ uint8_t counter = 255; counter++; /* unsigned wrap-around: defined */ printf(“a + b stored in uint8_t : %u\n”, sum8); printf(“a + b stored in int : %d\n”, sum); printf(“255 + 1 in uint8_t : %u\n”, counter); printf(“UINT_MAX + 1 (unsigned) : %u\n”, 0xFFFFFFFFu + 1u); return 0; }
Output (verified by compiling and running)
a + b stored in uint8_t : 44 a + b stored in int : 300 255 + 1 in uint8_t : 0 UINT_MAX + 1 (unsigned) : 0
SituationBehaviorDefined by the C standard?
Unsigned arithmetic exceeds the typeWraps around modulo 2NYes
Signed arithmetic exceeds the typeAnything: wrap, trap, or optimized awayNo (undefined behavior)
Result stored in a narrower typeConverted: high bits lostYes (implementation-defined for signed)
Division by zeroUnpredictableNo

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).

OperatorMeaningExampleValue
==equal to5 == 51
!=not equal to5 != 50
<less than3 < 51
>greater than3 > 50
<=less than or equal5 <= 51
>=greater than or equal3 >= 50
relational.c
#include <stdio.h> int main(void) { int x = 10, y = 20; printf(“x == y : %d\n”, x == y); printf(“x != y : %d\n”, x != y); printf(“x < y : %d\n”, x < y); printf(“x >= y : %d\n”, x >= y); int in_range = (x >= 5) + (x <= 15); /* the results are ordinary ints */ printf(“(x>=5) + (x<=15) = %d\n”, in_range); printf(“sizeof(x == y) = %zu\n”, sizeof(x == y)); return 0; }
Output (verified by compiling and running)
x == y : 0 x != y : 1 x < y : 1 x >= y : 0 (x>=5) + (x<=15) = 2 sizeof(x == y) = 4

Three classic traps

Trap 1 — = instead of ==: 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).
Trap 2 — chained comparison: 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).
Trap 3 — comparing floating-point values with ==: 0.1 + 0.2 == 0.3 is false because of rounding. Compare with a tolerance: fabsf(a - b) < 1e-6f.
range_trap.c
#include <stdio.h> #include <math.h> int main(void) { int x = 50; printf(“0 < x < 10 -> %d (wrong, always 1)\n”, 0 < x < 10); printf(“x>0 && x<10 -> %d (correct)\n”, x > 0 && x < 10); double s = 0.1 + 0.2; printf(“0.1+0.2 == 0.3 -> %d\n”, s == 0.3); printf(“fabs(s-0.3)<1e-9 -> %d\n”, fabs(s – 0.3) < 1e-9); return 0; }
Output (verified by compiling and running)
0 < x < 10 -> 1 (wrong, always 1) x>0 && x<10 -> 0 (correct) 0.1+0.2 == 0.3 -> 0 fabs(s-0.3)<1e-9 -> 1

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.

ABA && B (AND)A || B (OR)!A (NOT)
0 (false)0 (false)001
0 (false)non-zero011
non-zero0 (false)010
non-zeronon-zero110
AND needs both, OR needs one, NOT flips
A && B
true only when both are true
temp_ok && fan_on
A || B
true when at least one is true
btn1 || btn2
!A
true when A is zero
!error_flag
logical.c
#include <stdio.h> int main(void) { int a = 5, b = 0; printf(“a && b = %d\n”, a && b); printf(“a || b = %d\n”, a || b); printf(“!a = %d\n”, !a); printf(“!b = %d\n”, !b); printf(“!!a = %d (normalises any non-zero to 1)\n”, !!a); printf(“a & b = %d (bitwise, not logical)\n”, a & b); printf(“5 && 2 = %d, but 5 & 2 = %d\n”, 5 && 2, 5 & 2); return 0; }
Output (verified by compiling and running)
a && b = 0 a || b = 1 !a = 0 !b = 1 !!a = 1 (normalises any non-zero to 1) a & b = 0 (bitwise, not logical) 5 && 2 = 1, but 5 & 2 = 0
&& is not &: The logical operator tests whole values; the bitwise operator combines individual bits. 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).

short_circuit.c
#include <stdio.h> static int calls; static int check(const char *name, int value) { calls++; printf(” evaluating %s -> %d\n”, name, value); return value; } int main(void) { printf(“false && check(B):\n”); int r1 = check(“A”, 0) && check(“B”, 1); printf(” result %d, functions called so far: %d\n\n”, r1, calls); printf(“true || check(D):\n”); int r2 = check(“C”, 1) || check(“D”, 0); printf(” result %d, functions called so far: %d\n\n”, r2, calls); printf(“true && check(F):\n”); int r3 = check(“E”, 1) && check(“F”, 1); printf(” result %d, functions called so far: %d\n”, r3, calls); return 0; }
Output (verified by compiling and running)
false && check(B): evaluating A -> 0 result 0, functions called so far: 1 true || check(D): evaluating C -> 1 result 1, functions called so far: 2 true && check(F): evaluating E -> 1 evaluating F -> 1 result 1, functions called so far: 4
Evaluate A
left operand
➜
A false?
for &&
➜
Skip B
result = 0
➜
Else eval B
result = B

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 when a is true. Keep such side effects out of conditions.
Order matters: Reversing 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:

LevelOperatorsAssociativityExample
1() [] . -> postfix ++ --left to righta[i]++
2prefix ++ --, unary + - ! ~ * &, sizeof, castsright to left-x, !flag
3* / %left to righta * b % c
4+ -left to righta + b - c
5<< >>left to right1 << n
6< <= > >=left to righta < b
7== !=left to righta == b
8&left to righta & m
9^left to right
10|left to right
11&&left to righta && b
12||left to righta || b
13?:right to leftc ? x : y
14= += -= *= /= %= &= ^= |= <<= >>=right to lefta = b = 0
15,left to righti++, j--
precedence.c
#include <stdio.h> int main(void) { int a = 2, b = 3, c = 4; printf(“a + b * c = %d (multiplication first)\n”, a + b * c); printf(“(a + b) * c = %d (parentheses first)\n”, (a + b) * c); printf(“a – b – c = %d (left to right: (2-3)-4)\n”, a – b – c); printf(“10 / 2 * 5 = %d (left to right: (10/2)*5)\n”, 10 / 2 * 5); int x = 4; /* bit 2 is set */ printf(“x & 4 == 4 = %d (== binds tighter than &)\n”, x & 4 == 4); printf(“(x & 4) == 4 = %d (what you meant)\n”, (x & 4) == 4); int p = 0, q = 0, r = 1; printf(“p && q || r = %d (&& before ||)\n”, p && q || r); return 0; }
Output (verified by compiling and running)
a + b * c = 14 (multiplication first) (a + b) * c = 20 (parentheses first) a – b – c = -5 (left to right: (2-3)-4) 10 / 2 * 5 = 25 (left to right: (10/2)*5) x & 4 == 4 = 0 (== binds tighter than &) (x & 4) == 4 = 1 (what you meant) p && q || r = 1 (&& before ||)
The practical rule: Memorise only the broad order (unary, then * / %, then + -, then shifts, then comparisons, then bitwise, then &&, then ||, then ?:, then assignment) and use parentheses everywhere else. MISRA C requires parentheses around operands of mixed-precedence expressions; they cost nothing and make code review easier.

9. Common Mistakes With Basic Operators

Mistake 1 — integer division where a fraction was expected: average = sum / count; with integers truncates. Scale (sum * 100 / count) or convert before dividing.
Mistake 2 — divide first, multiply later: x / 4095 * 3300 yields 0 for any x below 4095. Multiply first.
Mistake 3 — = vs ==: An assignment inside a condition compiles but is almost never intended.
Mistake 4 — 0 < x < 10: Always true. Use &&.
Mistake 5 — & vs &&: Logical and bitwise operators give different results for the same operands.
Mistake 6 — relying on signed overflow: INT_MAX + 1 is undefined behavior; the optimizer may remove checks that assume it cannot happen.
Mistake 7 — side effects in the right operand of && or ||: They are skipped when the left side decides the result.
Mistake 8 — modulo of a negative number: -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 -Wconversion in 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 < 10 is 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

What is the difference between / and % in C?
/ gives the quotient and % gives the remainder of integer division. For 17 and 5: 17 / 5 is 3 and 17 % 5 is 2.
Why does 5 / 2 give 2 in C?
Both operands are integers, so the division is an integer division and the fractional part is discarded. Use 5 / 2.0 or (float)5 / 2 to get 2.5.
What is short-circuit evaluation?
In A && B the right operand is evaluated only if A is true; in A || B it is evaluated only if A is false. This lets you write guards like p != NULL && p->x.
What do relational operators return in C?
An int that is 1 when the relation is true and 0 when it is false.
What is the sign of the result of a % b when a is negative?
Since C99 the result has the sign of the dividend: -7 % 3 is -1 and 7 % -3 is 1.
Does signed integer overflow wrap around in C?
Not by definition: it is undefined behavior. Unsigned overflow does wrap modulo 2N. Do not depend on signed wrap-around.

Ready to practise?

Next: operators with output prediction, the integer division trap, short-circuit demos and a precedence workout.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →