Signed vs unsigned behavior on 8-bit MCU in Embedded C - Performance Comparison
We want to see how the program's running time changes when using signed or unsigned numbers on an 8-bit MCU.
How does the choice between signed and unsigned affect the number of steps the MCU takes?
Analyze the time complexity of the following code snippet.
#include <stdint.h>
void count_down_signed(int8_t start) {
while (start > 0) {
start--;
}
}
void count_down_unsigned(uint8_t start) {
while (start > 0) {
start--;
}
}
This code counts down from a starting number to zero using signed and unsigned 8-bit integers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that decreases the variable until it reaches zero.
- How many times: The loop runs once for each number from the start value down to 1.
As the start value increases, the number of loop steps grows roughly the same way for both signed and unsigned.
| Input Size (start) | Approx. Loop Iterations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 127 (max signed) | 127 |
Pattern observation: The loop count grows directly with the start value until the signed max is reached.
Time Complexity: O(n)
This means the running time grows linearly with the starting number, whether signed or unsigned.
[X] Wrong: "Unsigned variables always run faster than signed ones because they are simpler."
[OK] Correct: On an 8-bit MCU, both signed and unsigned decrement loops take similar steps; speed depends more on instructions than sign.
Understanding how signed and unsigned variables behave helps you write efficient code on small MCUs and shows you think about how hardware affects software.
"What if we changed the loop to count up from zero to the start value? How would the time complexity change?"