Firmware interviews: explain invariants before writing code
An interviewer can ask a deceptively small question about an array, queue or parser and then change one assumption. If you have only memorized the implementation, the follow-up can be difficult. A stronger approach is to define the valid input, what each operation promises, and what must remain true before and after the operation.
The contract
Consider a toy bounded counter whose legal values are zero through a declared maximum. An increment when full is rejected without changing the state. The invariant is that the value never exceeds the maximum for valid starting state. A test can examine the transition at the boundary rather than only a successful increment.
A small executable example
#include <stdbool.h>
#include <assert.h>
#include <stdio.h>
static bool increment(unsigned *v, unsigned max) {
if (*v >= max) return false;
++*v;
return true;
}
int main(void) {
unsigned v = 2;
assert(increment(&v, 3) && v == 3);
assert(!increment(&v, 3) && v == 3);
v = 0;
assert(!increment(&v, 0) && v == 0);
puts("invariant boundaries checked");
}
invariant boundaries checked
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
The function assumes a valid writable pointer. It also assumes valid initial state if the invariant is meant to hold globally; it does not repair an already invalid value. In a concurrent setting this check and update need a different synchronization contract. Calling the same function from an interrupt and a task without that contract is a new problem, not an optimization.
Checks to add in your own project
Explain why the increment cannot overflow under the stated conditions, then name the boundary cases and the expected results. If asked about performance, distinguish operation count from actual cycle measurements. When an implementation relies on hardware details, identify what the compiler and peripheral documentation must establish. This habit is useful in code review as well as in interviews, and avoids overclaiming what passing examples demonstrate.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.