Fixed-width integers (uint8_t, uint16_t, uint32_t) in Embedded C - Time & Space Complexity
When working with fixed-width integers like uint8_t, uint16_t, and uint32_t, it's important to understand how operations on these types affect program speed.
We want to see how the time to run code changes as the input size or number of operations grows.
Analyze the time complexity of the following code snippet.
#include <stdint.h>
void increment_array(uint8_t *arr, uint16_t size) {
for (uint16_t i = 0; i < size; i++) {
arr[i]++;
}
}
This code increases each element in an array of 8-bit unsigned integers by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Incrementing each element in the array.
- How many times: Exactly once for each element, controlled by the size variable.
As the array size grows, the number of increments grows at the same pace.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with the number of elements; doubling the size doubles the work.
Time Complexity: O(n)
This means the time to complete the task grows in a straight line with the number of elements.
[X] Wrong: "Using smaller fixed-width integers like uint8_t makes the loop run faster because each element is smaller."
[OK] Correct: The loop runs once per element regardless of integer size; the size affects memory but not how many times the loop runs.
Understanding how loops over fixed-width integers scale helps you explain performance clearly and shows you know how data size relates to processing time.
"What if we changed the array type from uint8_t to uint32_t but kept the same size? How would the time complexity change?"