Embedded C foundations
17 questions · beginner to advanced as applicable
100 free, scenario-based questions with plain-English explanations, C examples and follow-up answers. Start at your level. No account or purchase required.
Start with the basics · Take the free readiness check · Open course
17 questions · beginner to advanced as applicable
16 questions · beginner to advanced as applicable
17 questions · beginner to advanced as applicable
17 questions · beginner to advanced as applicable
16 questions · beginner to advanced as applicable
17 questions · beginner to advanced as applicable
Try each scenario before revealing the explanation. Then answer the follow-up without looking. The examples are illustrative; hardware-specific behavior must be checked against your target.
Pick an experiment. Predict what will happen, step through the picture, then test your understanding.
Choose a track, explain each answer aloud, reveal the model explanation and rate your own reasoning. Timers are advisory. Restarting resets the current session; no answers are transmitted or saved.
Remaining suggested time:
Scenario: Imagine an 8-bit unsigned counter that records events. What happens after 255?
Eight bits represent 256 distinct patterns, from 0 to 255. If the result is stored back into an unsigned 8-bit object, 256 becomes 0. This is wraparound, not an automatic error. A signed type has different rules; signed arithmetic overflow is undefined in C.
uint8_t count = 255;
count++; /* count becomes 0 */Follow-up: What would you change if the counter must never wrap?
Check the limit before incrementing, saturate or use a wider counter according to the requirements.
Scenario: A function needs to update a caller's sensor reading without returning a new value.
A pointer stores an address. Passing that address lets a function access the original object. The object must still exist, the pointer must be valid, and its type must be appropriate. A pointer is not the value stored at that address.
void reset(int *value) { *value = 0; }
int reading = 42;
reset(&reading);Follow-up: What happens if reset receives a null pointer?
Dereferencing it is invalid; validate it or document a non-null contract.
Scenario: A function receives a buffer of sensor samples and calculates the average.
In most expressions an array becomes a pointer to its first element. A function parameter written int a[] is adjusted to int *a. The pointer does not carry the array length. Pass a count explicitly and check it before accessing elements.
int first(const int *a, size_t n, int *out) {
if (!a || !out || n == 0) return 0;
*out = a[0]; return 1;
}Follow-up: Why is sizeof(a) inside this function not the array size?
It measures the pointer object, not the caller's array.
Scenario: A simulated status byte contains independent flags. Set bit 2, clear bit 2, and test it.
A mask has a 1 in the chosen position. OR sets that bit; AND with the inverted mask clears it; AND with the mask tests it. XOR toggles it. Check that the bit index fits the type before shifting.
unsigned flags = 0;
flags |= 1u << 2;
flags &= ~(1u << 2);
int set = (flags & (1u << 2)) != 0;Follow-up: Would this always be safe on a peripheral register?
No. Some registers have special write semantics or concurrent updates. Consult the device documentation.
Scenario: On a typical target with 4-byte int alignment, compare a char followed by an int.
Alignment means some objects work best or must begin at particular address boundaries. The compiler may leave unused bytes, called padding, between fields and at the end so each field and each array element is correctly aligned. The exact layout depends on the target.
struct Sample { char tag; int value; };
/* Often 8 bytes, not 5, on a typical 32-bit ABI. */Follow-up: Can you send the raw struct directly as a network message?
Not portably. Padding, byte order and integer sizes can differ; explicitly serialize fields.
Scenario: A main loop and an interrupt both update a shared counter. Both increments appear to run, but the count sometimes increases by only one.
Atomic means an operation behaves as one indivisible action with respect to other relevant execution contexts. An increment can load the old value, add one, then store it. If the other context updates between those steps, one update can be lost. Volatile tells the compiler that accesses to an object are observable; it does not make a compound operation indivisible or provide thread synchronization.
/* Illustrative interleaving, initial count = 5:
A reads 5; B reads 5; B writes 6; A writes 6.
Expected 7, observed 6. */Follow-up: How would you protect the update?
Use a platform-appropriate critical section or a suitable atomic operation. Check interrupt safety and latency constraints.
Scenario: Two uint8_t operands are added before being assigned to another uint8_t.
In C, small integer types generally promote to int when int can represent all their values. Arithmetic occurs in the promoted type. Assignment to the smaller unsigned type then reduces the result modulo its range. Distinguish the calculation type from the destination type.
uint8_t a = 200, b = 100;
int sum = a + b; /* 300 */
uint8_t low = a + b; /* 44 */Follow-up: How would you detect overflow before storing the result?
Compare the wider result with UINT8_MAX before converting.
Scenario: Two C source files need to share a configuration value.
A declaration tells the compiler a name and its type. A definition supplies the object or function itself. A header can declare a shared object using extern; exactly one source file should define it. Including a definition in multiple files can cause link errors.
/* header */ extern int config;
/* one source file */ int config = 3;Follow-up: Why not define the object in every source file?
The linker may encounter multiple external definitions of the same symbol.
Scenario: A function needs to remember how many times it has been called.
An ordinary local variable typically exists for one invocation. A static local object exists for the entire execution and retains its value between calls. Static storage duration is not the same as thread safety; simultaneous updates still need coordination.
unsigned calls(void) {
static unsigned n;
return ++n;
}Follow-up: Where is a static local usually placed?
In a data or zero-initialized section, depending on initialization and the linker configuration.
Scenario: A parser should read incoming bytes without modifying them.
Read declarations from the identifier outward. const uint8_t *p means the pointed-to bytes cannot be modified through p. uint8_t *const p means the pointer cannot be reassigned. Neither automatically guarantees that another alias cannot modify the same bytes.
const uint8_t *p = buffer;
uint8_t *const fixed = buffer;Follow-up: Does const always put data in flash?
No. Placement depends on storage duration, linker configuration and target.
Scenario: Store the text OK in a C string.
A C string ends with a zero-valued character. The two visible characters require three bytes including that terminator. A character array is not necessarily a valid string; functions expecting strings need a terminator within accessible memory.
char ok[] = "OK"; /* sizeof ok is 3 */Follow-up: What does strlen count?
Characters before the first zero terminator, excluding the terminator.
Scenario: A function compares an error value of -1 against an unsigned count.
The usual arithmetic conversions may convert a signed operand to unsigned before comparison. A negative value converted to unsigned becomes a large modulo value. Therefore validate negative values before mixing signed and unsigned quantities.
int n = -1;
unsigned limit = 10;
/* n < limit is false on typical equal-width int types. */Follow-up: How should an error-return value be handled?
Check the error condition first; convert only a validated nonnegative value.
Scenario: Two devices exchange the number 0x1234 as two bytes.
Endianness describes the order of bytes in a multibyte representation. Little endian puts the least significant byte first; big endian puts the most significant byte first. A protocol must define its own byte order rather than relying on a host representation.
uint16_t v = 0x1234;
uint8_t hi = (uint8_t)(v >> 8);
uint8_t lo = (uint8_t)v;Follow-up: Does endianness change the mathematical value?
No. It changes how that value is represented in bytes.
Scenario: A mask helper receives a configurable bit number.
C requires the shift count to be nonnegative and smaller than the width of the promoted left operand. A shift by 32 on a 32-bit operand is undefined, not guaranteed to produce zero. Validate the index before shifting and choose an appropriate unsigned operand.
if (bit < 32u) {
uint32_t mask = UINT32_C(1) << bit;
}Follow-up: Why use an unsigned operand?
It avoids additional restrictions associated with signed left shifts.
Scenario: Compact a buffer by moving a portion toward its beginning.
memcpy requires that source and destination regions do not overlap. memmove supports overlap as if bytes were copied through a temporary region. Both still require valid accessible regions of the specified size.
memmove(buf, buf + 2, len - 2); /* assuming len >= 2 */Follow-up: Does memmove validate buffer lengths?
No. The caller must establish bounds.
Scenario: A formatter returns the address of a local character buffer.
An automatic local object's lifetime ends when execution leaves its scope. A pointer to that expired object cannot safely be used. Instead let the caller supply storage, return a value, or deliberately choose suitable persistent storage.
void format(char *out, size_t cap);Follow-up: What is the drawback of a static return buffer?
Subsequent calls can overwrite it, and concurrent calls may conflict.
Scenario: A developer tries to interpret an integer's bytes by casting its address to a float pointer.
C restricts which lvalue types may access an object's stored value. Incompatible pointer casts can produce undefined behavior even if sizes match. Copying bytes with memcpy avoids that aliasing violation, but the destination representation must still be valid for the intended interpretation.
/* Inspect an object's representation through unsigned char. */
const unsigned char *bytes = (const unsigned char *)&value;Follow-up: Does memcpy guarantee a portable numeric conversion?
No. Copying a representation is different from converting a value.
Scenario: Find a target in a sorted table of 1,024 sensor calibration values.
Linear search checks candidates one by one. Binary search checks the middle value and discards the half that cannot contain the target. Repeating this gives logarithmic growth, O(log n), rather than linear growth, O(n). The array must be sorted; roughly ten halvings reduce 1,024 candidates to one.
/* On a half-open interval [lo, hi): */
size_t mid = lo + (hi - lo) / 2;Follow-up: Why use lo + (hi - lo) / 2?
It avoids overflow from adding two potentially large indices, assuming lo <= hi.
Scenario: Sensor readings arrive faster than a display can process them for a short period.
A queue keeps items in arrival order: first in, first out (FIFO). It separates the producer from the consumer. A bounded queue must define what happens when it fills, since memory is limited.
/* A, B, C arrive; removal order: A, B, C. */Follow-up: What if the producer is permanently faster?
No finite queue solves that indefinitely; reduce production, increase consumption or define a loss policy.
Scenario: A recursive function traverses a tree on a device with limited stack memory.
A stack is last in, first out. Function calls typically use stack frames for saved state and local data. Deep or unbounded recursion can exhaust available stack space. An iterative approach with an explicitly bounded work stack can make memory usage easier to reason about.
/* 100 nested calls × 32 bytes per frame
is roughly 3,200 bytes, excluding other usage. */Follow-up: Does every recursive call necessarily use a new frame?
Not always; optimization can alter frame usage. Measure or bound the actual target build.
Scenario: A serial data stream produces bytes that another task consumes.
A ring buffer uses a fixed array and read/write indices that wrap at the end. Items stay where they are; only indices move. This gives constant-time enqueue/dequeue for a single item. A design must distinguish full from empty, for example by reserving one slot.
/* Capacity N, next index: */
next = (head + 1) % N;
/* With one reserved slot: full if next == tail. */Follow-up: Is a ring buffer automatically thread safe?
No. Ownership of indices, memory ordering and synchronization depend on the producer/consumer model.
Scenario: A device needs a bounded number of same-sized message objects.
A pool preallocates blocks and tracks which are free. Allocation can be predictable and external fragmentation within the pool is avoided for equal-sized blocks. The trade-off is fixed capacity and possibly wasted space inside blocks.
/* 16 blocks × 64 bytes = 1024 bytes
of payload storage, plus bookkeeping. */Follow-up: What should happen when all blocks are occupied?
Return a clear failure or apply a defined backpressure policy; do not silently overwrite live objects.
Scenario: A configuration table holds eight keys and is searched occasionally.
Hash tables can offer average constant-time lookup, but require extra storage and collision handling. Worst-case lookup can degrade to linear time. For a tiny table, a simple array may be smaller and easier to validate.
/* Eight entries: a linear search needs at most
eight key comparisons. */Follow-up: When would a sorted array be attractive?
When updates are rare and searches frequent, binary search can provide bounded logarithmic comparisons.
Scenario: Insert a new item at the front of a packed list of 100 readings.
A packed array stores elements consecutively. Inserting at the front requires moving existing elements to create space, so work grows with the number of elements. Appending to an array with free capacity can be constant time.
/* Shift existing elements only after checking capacity. */
memmove(a+1,a,n*sizeof *a);Follow-up: When is this acceptable?
For small lists or rare insertions, simplicity and locality may outweigh the cost.
Scenario: Maintain a collection whose elements need not occupy adjacent addresses.
Each node contains data and a link to the next node. Inserting after a known node can be constant time, but finding a node can take linear time. Links consume memory and scattered nodes may reduce cache locality.
struct Node { int value; struct Node *next; };Follow-up: Is a linked list always better than an array?
No. Choose according to access patterns, memory overhead and allocation constraints.
Scenario: A lookup reads the item at a known valid array index.
O(1) means the work is bounded independently of input size in the chosen model. It does not mean exactly one instruction or identical elapsed time. Hardware caches and compiler output affect actual timing.
int value = a[index]; /* valid index */Follow-up: Does O(1) prove a real-time deadline?
No. A concrete timing bound is still needed.
Scenario: A task manager must select the smallest deadline from pending jobs.
A binary min-heap keeps the smallest key at its root. Insertions and removals restore the heap property in logarithmic time. It is useful when repeatedly selecting the next minimum, without fully sorting every entry.
/* For zero-based heap index i: parent=(i-1)/2 for i>0. */Follow-up: Is the entire heap array sorted?
No. Only the parent-child ordering is guaranteed.
Scenario: A producer emits bursts while a consumer occasionally pauses.
Capacity must cover the maximum accumulated backlog under stated assumptions. Estimate arrivals during the longest service interruption and account for existing queued items. If no finite bound exists, define a loss or backpressure policy.
/* At 100 samples/s, a 0.2 s pause adds about 20 samples. */Follow-up: Why is the average arrival rate insufficient?
Bursts and worst-case service gaps determine peak backlog.
Scenario: Track 32 fixed slots with minimal metadata.
A bitmap uses one bit per slot to represent free or occupied state. Searching for a free bit and updating it can be compact, but concurrent allocation needs synchronization. Reserve unused bits when the slot count is not a word multiple.
uint32_t used = 0;
used |= UINT32_C(1) << slot; /* slot < 32 */Follow-up: How much metadata is needed for 32 slots?
Four bytes for the bitmap itself, excluding other bookkeeping.
Scenario: A search repeatedly chooses the same midpoint.
A binary search invariant specifies which indices may contain the answer. Every iteration must shrink that interval. Mixing inclusive and half-open boundaries can prevent progress or access outside the array. Pick one convention and test empty and one-element intervals.
/* Half-open interval: if a[mid] < key, lo = mid+1;
otherwise hi = mid for a lower-bound search. */Follow-up: What is a useful termination invariant?
The interval length hi-lo decreases on every iteration until it is zero.
Scenario: Two arrays contain time-ordered samples.
Keep one index into each array, compare the current values and emit the smaller one. Each step advances at least one index. Total work is linear in the combined lengths; output capacity and equal-key ordering must be specified.
/* While both have items, choose the smaller head;
then emit remaining items. */Follow-up: Can you avoid a large output buffer?
Yes, if the consumer accepts items incrementally.
Scenario: Review a circular queue implementation for correctness.
An invariant is a property that must hold at defined points during execution. For a queue, indices must stay within capacity and occupancy must remain representable. State the invariant before writing operations; then prove each operation preserves it.
/* Example invariant: 0 <= count <= capacity. */Follow-up: What boundary tests follow from this invariant?
Empty, full, transition across wraparound, and repeated insert/remove cycles.
Scenario: A problem has a large table of overlapping subproblems but very little RAM.
Dynamic programming saves intermediate results to avoid repeated computation. The table can be too large for constrained hardware. Consider reducing states, rolling rows, recomputation or a different algorithm, based on the required memory and time bounds.
/* If row i depends only on row i-1, retain two rows. */Follow-up: Is a faster algorithm always preferable?
No. Memory, timing predictability, complexity and energy can dominate.
Scenario: A periodic timer signals that a sensor sample is ready.
An interrupt temporarily transfers execution to a handler so the CPU can respond to an event. Long handlers can delay other work and affect response time. A common pattern is to capture essential information and defer heavier processing to normal code.
/* Conceptual pattern:
handler: acknowledge event, record pending work
main task: process pending work */Follow-up: Can a handler call any normal library function?
Not necessarily; check reentrancy, blocking behavior and the platform's interrupt-context rules.
Scenario: A single physical press causes several rapid changes in the input signal.
Mechanical contacts can bounce as they settle. Software that counts every transition may interpret one press as many. Debouncing accepts a change only after suitable stability or timing criteria, with a delay chosen for the actual switch and application.
/* Example: sample periodically and accept
a new state after several consistent samples. */Follow-up: Why not simply block for a long delay?
Blocking may delay unrelated work; use a nonblocking state machine when responsiveness matters.
Scenario: A status indicator must change every 500 ms while the main loop keeps processing messages.
A state machine remembers the current state and changes it when a condition is met. Instead of sleeping, compare elapsed time with the interval and return quickly. Unsigned tick subtraction can handle wraparound when elapsed time is within the counter's range.
if ((uint32_t)(now - last) >= 500u) {
last = now;
state = !state;
}Follow-up: What if the loop runs late?
Decide whether to preserve phase, catch up or skip missed intervals; each has different timing behavior.
Scenario: Two tasks use the same shared data and the result depends on which task runs first.
A race condition is a timing-dependent correctness problem. A C data race is more specific: conflicting accesses in different threads, at least one non-atomic, without the necessary happens-before ordering. A C data race causes undefined behavior. Protect shared state using a suitable synchronization design.
/* Prefer one owner for shared state, or use
a lock/atomic operation appropriate to the context. */Follow-up: Does a mutex solve every concurrency issue?
No. Deadlock, priority inversion, incorrect lock scope and interrupt-context restrictions still matter.
Scenario: A periodic task must finish within 1 ms. Most calls take 0.1 ms, but rare calls take 2 ms.
A deadline concerns whether work finishes on time, not just its average duration. Rare slow paths, contention and interrupt interference can cause missed deadlines. Analyze worst-case behavior under realistic workloads and distinguish measured maxima from proven bounds.
/* 999 calls at 0.1 ms + one at 2 ms:
average ≈ 0.102 ms, yet one deadline missed. */Follow-up: How would you investigate the rare delay?
Instrument execution, reproduce representative load, inspect contention and bound the relevant slow paths.
Scenario: A device updates a configuration record and loses power midway.
Do not assume a multi-step write is indivisible. Keep a previously valid record until the replacement is safely committed. A recovery strategy can use versioning, integrity checks and a commit marker, subject to the storage device's actual programming and erase guarantees.
/* Conceptual record: version, payload, integrity
check, commit state. Validate on startup. */Follow-up: Does a checksum alone guarantee recovery?
No. It helps detect corruption, but record selection, write ordering, erase behavior and recovery must also be designed.
Scenario: A parser should correctly handle empty, valid and truncated input buffers.
Separate portable logic from hardware access. Pass input explicitly, test normal and boundary cases, and use host compiler warnings and sanitizers where available. Then validate hardware-dependent assumptions on the target. Passing host tests does not prove timing or peripheral behavior.
/* Cases: empty input, shortest valid message,
maximum length, truncated message, invalid field. */Follow-up: What would you test on the real board?
Actual timing, hardware interfaces, memory limits, interrupt behavior and integration with the rest of the firmware.
Scenario: A device must check whether a new sensor sample is available.
Polling checks a condition repeatedly; interrupts notify execution when an event occurs. Polling can be simple and predictable, while interrupts can reduce unnecessary work. The best choice depends on response-time needs, event rate and power constraints.
/* Poll: if (sample_ready()) process_sample(); */Follow-up: When can polling be preferable?
When work is periodic, response bounds are adequate and interrupt complexity is unnecessary.
Scenario: A program becomes unresponsive after an unexpected fault.
A watchdog is a timer that requires periodic servicing; if software stops meeting its health conditions, it can trigger recovery such as a reset. Servicing it blindly can hide failures. Design health checks and investigate the root cause rather than relying on resets alone.
/* Conceptual: service watchdog only after required health checks. */Follow-up: Does a watchdog prevent all software failures?
No. It detects selected failures and provides a recovery mechanism.
Scenario: A sensor read fails but the caller keeps using its previous output.
An error return communicates that the requested operation did not succeed. Ignoring it may use stale or invalid data. Define the output contract on failure and make the caller choose retry, fallback or a reported error.
if (read_sample(&sample) != 0) {
report_error();
}Follow-up: Should every error be retried?
No. Permanent errors and bounded timing requirements may make retries inappropriate.
Scenario: A test occasionally returns an incorrect measurement.
Start with a reproducible observation, record relevant inputs and expected output, and narrow the suspected cause. Add targeted instrumentation and compare successful and failed cases. Change one hypothesis at a time and verify a fix with a regression test.
/* Record test seed, input, expected and observed output. */Follow-up: Why preserve the failing input?
It makes the failure reproducible and supports a regression test.
Scenario: A peripheral operation may never report completion.
A timeout bounds waiting when an expected event does not arrive. It should use a suitable time source, define the failure response, and be tested at the boundary. It is not a substitute for checking completion status.
/* Conceptual: check completion; otherwise compare elapsed time. */Follow-up: What if the clock stops in a low-power mode?
Choose a time source that meets the timeout requirements across that mode.
Scenario: A high-priority task waits for a resource held by a low-priority task.
If a medium-priority task preempts the low-priority owner, the high-priority task can be indirectly delayed. Priority inheritance or other scheduling protocols can bound some forms of inversion. Keep critical sections short and analyze dependencies.
/* High waits for Low; Medium delays Low. */Follow-up: Does priority inheritance eliminate deadlocks?
No. Lock ordering and resource design still matter.
Scenario: Two threads need the same two resources in different orders.
A deadlock occurs when tasks wait indefinitely for conditions that cannot be satisfied, such as each holding a lock the other needs. A consistent lock acquisition order can prevent circular waiting in this example.
/* Both threads acquire A before B, release in reverse order. */Follow-up: Can a timeout alone prove correctness?
No. It may permit recovery, but the underlying resource protocol still needs validation.
Scenario: A DMA controller fills a buffer while the CPU reads samples.
DMA transfers can run independently of normal CPU execution. If the CPU reads before the transfer is complete or reuses an active buffer, it may observe inconsistent data. Define ownership, completion and any cache maintenance required by the platform.
/* States: free -> DMA-owned -> CPU-owned -> free. */Follow-up: Is volatile enough for cache coherency?
No. Coherency and ordering require the target's documented mechanisms.
Scenario: Represent a fractional value on a system using integer arithmetic.
Fixed-point stores a scaled integer. For a scale of 256, the integer 384 represents 1.5. Addition requires compatible scales; multiplication requires rescaling and sufficient intermediate width. Choose rounding and overflow rules explicitly.
int32_t scaled = 384; /* scaled / 256 = 1.5 */Follow-up: What is the trade-off?
Resolution and range compete for the available bits.
Scenario: A corrected parser previously failed for an empty input.
A regression test captures a previously observed failure and checks the expected behavior. It should fail before the fix and pass afterward. Include nearby boundary cases to avoid fixing only the exact example.
/* Assert parse(empty_input) returns the documented error. */Follow-up: Does a regression test replace exploratory testing?
No. It protects known behavior; new defects still require broader testing.
Scenario: A local array is passed to a helper.
An array owns its elements; in most expressions its name converts to a pointer to its first element. The pointer has no length information. On the original array, sizeof measures all elements.
int a[4]; size_t n = sizeof a / sizeof a[0];Follow-up: Does sizeof work inside a pointer parameter?
No, it measures the pointer.
Scenario: A loop adds readings to a local sum.
An automatic local object without an initializer may have an indeterminate value. Reading it can lead to undefined behavior. Initialize the accumulator to the identity before processing.
int sum = 0; for(size_t i=0;i<n;++i) sum += a[i];Follow-up: Are static objects initialized?
Yes, to the appropriate zero value if not explicitly initialized.
Scenario: A display converts 1500 ms into seconds.
Integer division truncates toward zero in modern C. Thus 1500 divided by 1000 yields one, with a remainder of 500. Converting the result to floating point does not recover the fraction.
int sec=1500/1000, rem=1500%1000;Follow-up: What about division by zero?
Integer division by zero has undefined behavior.
Scenario: A helper receives a buffer length.
The size_t type is the unsigned integer type returned by sizeof. It represents object sizes on the implementation and avoids narrowing lengths to int. Unsigned subtraction still needs bounds checks.
size_t remaining = cap - used; /* used <= cap */Follow-up: Can size_t be negative?
No; unsigned arithmetic wraps modulo its range.
Scenario: A parser checks offset plus length.
Addition can wrap before comparison. First check that the offset is within capacity, then compare the length against capacity minus offset. Short circuiting ensures the subtraction occurs only when valid.
if(off<=cap && len<=cap-off) parse();Follow-up: Does the check validate a null buffer?
No, validate the underlying object separately.
Scenario: A driver exposes a completion callback.
A function pointer refers to a function of a compatible type. It allows modules to invoke callbacks without depending on a concrete implementation. Optional callbacks must be checked before calling.
typedef void (*done_fn)(int); if(done) done(status);Follow-up: Can incompatible function pointers be called?
No, calling through an incompatible type is undefined.
Scenario: A parser has idle and payload states.
An enumeration gives meaningful names to integer constants and makes transitions readable. Compiler diagnostics can help identify missing switch cases. Do not assume a fixed wire representation.
enum state { IDLE, HEADER, PAYLOAD };Follow-up: Does an enum prevent invalid state values?
No; validate external inputs and handle unexpected states.
Scenario: A macro squares an addition expression.
Macro replacement is textual, so unparenthesized arguments may bind operators differently than intended. Parentheses solve precedence but do not prevent evaluating an argument multiple times.
#define SQUARE(x) ((x)*(x))Follow-up: What is a safer alternative?
A typed inline function evaluates the argument once.
Scenario: Two source dependencies include one header.
A guard suppresses repeated inclusion within the same translation unit, preventing duplicate type definitions. It does not prevent duplicate external symbol definitions across multiple source files.
#ifndef DRIVER_H
#define DRIVER_H
/* declarations */
#endifFollow-up: Where should external functions be defined?
In one source file, with declarations in headers.
Scenario: Two buffers are processed by one helper.
Restrict establishes aliasing requirements for accesses to modified objects during its scope. It can enable optimization; violating the contract can produce undefined behavior. It is not a runtime overlap detector.
void add(size_t n,int *restrict dst,const int *restrict src);Follow-up: Does restrict check overlap at runtime?
No, the compiler may assume the contract holds.
Scenario: A packet has a 32-bit field at an odd offset.
Casting a byte pointer to a wider typed pointer may violate alignment or object access rules even on tolerant hardware. Copy bytes into aligned storage or decode explicitly and handle endianness.
uint32_t v; memcpy(&v, bytes+off, sizeof v);Follow-up: Does memcpy fix byte order?
No; it preserves the bytes.
Scenario: A configuration has optional fields.
Designated initializers identify members by name rather than position, making intent clear. Unspecified members are initialized as if they had static storage duration, providing predictable defaults.
struct cfg c={.rate=100,.enabled=1};Follow-up: What happens when an optional field is added?
It receives the appropriate zero value unless explicitly initialized.
Scenario: A message header has variable payload size.
A flexible array member is the last member of a structure with another named member. Its elements are not included in sizeof the structure. Allocate enough additional storage with checked size arithmetic.
struct msg {size_t len; unsigned char bytes[];};Follow-up: Can sizeof tell you payload length?
No, retain explicit length metadata.
Scenario: A protocol needs a specific integer width.
A static assertion evaluates a constant expression during compilation and produces a diagnostic when it is false. It catches assumptions about types or limits without replacing runtime input validation.
_Static_assert(sizeof(uint32_t)*CHAR_BIT==32,"width");Follow-up: Can it validate received packet lengths?
No, those are runtime values.
Scenario: A function declares a variable-length array.
For a variable-length array type, sizeof may be evaluated at runtime. Variable stack usage can be unsuitable for constrained devices, and VLA support varies by C version and implementation.
size_t bytes=n*sizeof(int); /* check multiplication first */Follow-up: What bound prevents size multiplication overflow?
Require n <= SIZE_MAX / sizeof(int).
Scenario: A message holds one of two value types.
A union overlays storage for alternatives, reducing the storage needed. A separate tag identifies which member is logically active. Layout and representation depend on the implementation, so use explicit serialization.
struct value {int tag; union {int i;float f;} data;};Follow-up: Is the raw struct a portable wire format?
No; serialize the tag and active data explicitly.
Scenario: An expression modifies one variable twice.
C does not impose a universal operand evaluation order. Unsequenced modifications of the same scalar object can lead to undefined behavior. Separate modifications into statements to specify the order clearly.
int a=i++; int b=i++; int result=a+b;Follow-up: Do parentheses establish sequencing?
No; they change grouping.
Scenario: A table of device IDs is unsorted.
Linear search compares each element until a match or the end. It needs no sorted input and constant auxiliary space. The worst-case number of comparisons grows linearly with the table size.
for(size_t i=0;i<n;++i) if(a[i]==key)return i;Follow-up: When is linear search preferable?
For small unsorted tables where sorting is unnecessary.
Scenario: A short calibration table is nearly sorted.
Insertion sort grows a sorted prefix by moving larger entries and inserting the next value. It uses constant extra space and performs well on nearly sorted data, but its worst-case time is quadratic.
while(j>0&&a[j-1]>x){a[j]=a[j-1];--j;} a[j]=x;Follow-up: What makes this version stable?
Equal entries are not shifted past one another.
Scenario: Equal timestamps should keep arrival order.
A stable sort preserves the relative order of elements with equal keys. That property is important when a prior ordering conveys meaning. In merging, taking equal left keys first preserves their order.
if(left.key<=right.key)take_left();else take_right();Follow-up: Are all efficient sorts stable?
No; stability depends on implementation.
Scenario: A table contains duplicate values.
A lower bound search maintains a half-open interval and moves the upper boundary when the midpoint is not smaller than the key. The returned position is the first value at least as large, or n.
while(lo<hi){size_t m=lo+(hi-lo)/2;if(a[m]<key)lo=m+1;else hi=m;}Follow-up: What if the key is absent?
The result is its insertion position; check equality separately.
Scenario: A work list needs operations at both ends.
A double-ended queue supports adding and removing elements at either end. A bounded circular array permits constant-time end operations, provided capacity and full and empty states are tracked correctly.
/* push_front, push_back, pop_front, pop_back */Follow-up: Are middle insertions constant time?
Not in a simple array-backed deque.
Scenario: A rolling maximum is needed for recent samples.
A decreasing monotonic queue retains only candidates that may become the maximum. Remove expired indices from the front and dominated entries from the back. Each index enters and exits at most once.
while(!empty()&&back_value()<=x)pop_back();Follow-up: What else must the queue store?
Indices or timestamps to identify expired entries.
Scenario: Samples arrive after capacity is reached.
A full buffer needs an explicit policy: reject the incoming sample, discard the oldest, or report backpressure. Overwriting may be fine for recent history but not loss-sensitive messages. Record losses.
if(full()){++dropped;return false;}Follow-up: Does overwriting eliminate synchronization?
No, ownership still needs coordination.
Scenario: Two configuration keys have equal hashes.
Separate chaining keeps multiple entries per bucket and compares actual keys rather than hashes alone. A bounded pool can constrain memory. Lookup may still degrade if many entries share one bucket.
size_t bucket=hash(key)%bucket_count;Follow-up: What is the worst case?
A single long chain produces linear lookup.
Scenario: A lookup fails after a preceding key is deleted.
An open-addressed table searches along a probe sequence. Marking a deleted slot as never used may cause early termination before later keys. A deletion marker keeps the chain searchable until compaction.
enum slot { EMPTY, OCCUPIED, DELETED };Follow-up: What if tombstones accumulate?
Searches slow down; rebuild using a bounded policy.
Scenario: A dependency tool represents modules as vertices.
An adjacency list stores the neighbors of each vertex without allocating a full matrix. Fixed arrays of offsets and edges can represent sparse graphs predictably. Traversal must handle already visited vertices.
for(size_t i=offset[v];i<offset[v+1];++i)visit(edge[i]);Follow-up: When is a matrix simpler?
For small dense graphs or frequent direct adjacency tests.
Scenario: A graph needs shortest unweighted paths.
Breadth-first search uses a queue to explore vertices in increasing distance from the start. Mark vertices when they enter the queue to avoid duplicates. It finds shortest paths in unweighted graphs.
seen[start]=true;enqueue(start); /* FIFO expansion */Follow-up: How can queue memory be bounded?
Allocate capacity for the maximum vertex count.
Scenario: Module initialization has dependencies.
A topological order exists only for a directed acyclic graph. Kahn's algorithm removes vertices with no incoming edges and updates neighbors. If fewer vertices are removed than exist, a cycle remains.
if(processed!=vertex_count)return CYCLE_ERROR;Follow-up: Can multiple valid orders exist?
Yes, when multiple vertices have no remaining dependencies.
Scenario: A scheduler tracks 32 active slots.
A bitset uses one bit per Boolean member, saving storage for a bounded dense universe. Validate the index before shifting and use an unsigned mask. Changes to shared words require coordination.
if(i<32)active |= UINT32_C(1)<<i;Follow-up: Is changing a bitset automatically thread-safe?
No; shared updates require synchronization.
Scenario: A collection sometimes grows during a deadline-sensitive task.
Amortized analysis bounds total work over a sequence, not the cost of every operation. An occasional expensive resize can violate a deadline despite low average work. Fixed capacity can avoid that cost.
/* reserve bounded capacity before processing */Follow-up: What matters for deadlines?
Worst-case latency and bounded resource use.
Scenario: A sample history receives many sum queries.
Prefix sums store cumulative totals, so the sum over a half-open range is the difference between two prefix values. Construction is linear and queries constant time. The accumulator must be sufficiently wide.
int64_t total=prefix[end]-prefix[start];Follow-up: What if samples frequently change?
Rebuilding can be expensive; consider an update-aware structure.
Scenario: A parser matches commands sharing prefixes.
A trie stores strings as paths of characters and supports prefix matching. It reduces repeated prefix comparisons but can use substantial node memory. Compact tables or sparse children can reduce space.
/* each node has a terminal flag and indexed children */Follow-up: How do you bound traversal?
Limit input length and validate character indices.
Scenario: A module starts before configuration is loaded.
Initialization establishes required state and verifies resources before normal work. Explicit readiness prevents calls before setup succeeds and makes failure handling and repeated initialization easier to reason about.
if(!initialized)return NOT_READY;Follow-up: Should initialization failure be ignored?
No, report it or enter a defined application state.
Scenario: The wall clock changes during a timeout.
A monotonic source is not affected by wall-clock corrections. For modular tick counters, unsigned subtraction measures elapsed time across wraparound if the actual interval fits within the counter range.
if((uint32_t)(now-start)>=duration)expired();Follow-up: What if a whole counter period passes?
Elapsed time is ambiguous; enforce a sampling bound.
Scenario: Several periodic jobs share an execution loop.
Cooperative tasks voluntarily return control rather than being preempted by the scheduler. Each must finish within a bounded time or yield in short steps. Blocking a task delays other work.
for(;;){poll_inputs();update_state();service_output();}Follow-up: What does preemption change?
A runnable higher-priority task may interrupt lower-priority work.
Scenario: A library calls user code on its event thread.
A blocking callback delays unrelated events and can deadlock if it waits for work requiring the same dispatch thread. Record the event and defer longer work to an appropriate execution context.
void on_event(int e){enqueue_event(e);}Follow-up: What if the queue fills?
Use an explicit failure policy and record the loss.
Scenario: A routine may be invoked while already active.
A reentrant function can be entered again before a previous invocation completes. It avoids conflicting shared mutable state and uses appropriately owned inputs. Reentrancy is not the same as being protected by a lock.
int sum2(int a,int b){return a+b;}Follow-up: Is shared static scratch storage usually reentrant?
Not without a design preventing conflicting accesses.
Scenario: One thread publishes initialized data to another.
A release store and an acquire load that observes it can establish a happens-before relationship for preceding writes. This permits publication of ordinary data under a correct ownership protocol. Volatile is insufficient.
atomic_store_explicit(&ready,true,memory_order_release);Follow-up: What does the receiver use?
An acquire load observing the published value before reading data.
Scenario: Two tasks update a multi-field object.
Ordering constrains how accesses are observed but does not prevent two writers interfering. A mutex or correctly designed ownership protocol protects the whole invariant. Select synchronization for the complete operation.
lock(&m);update_pair();unlock(&m);Follow-up: Does an atomic flag protect all accesses?
Only when all participants follow a correct protocol.
Scenario: A peripheral sometimes reports busy.
A bounded policy limits attempts or total elapsed time and returns an explicit result when the resource stays unavailable. This prevents endless waiting and allows the caller to defer work or report failure.
for(unsigned i=0;i<3;++i){if(try_read())return OK;}return BUSY;Follow-up: Why might immediate retries fail?
The resource may need time to become available.
Scenario: A receiver detects corrupted messages.
A checksum detects specified classes of corruption but generally cannot reconstruct original data. Error-correcting codes add structured redundancy to correct errors within their capability. Neither detects all possible errors.
if(computed_crc!=received_crc)return BAD_FRAME;Follow-up: Does a CRC authenticate a sender?
No, it detects accidental errors rather than authenticating.
Scenario: A retry delivers the same configuration command twice.
An idempotent operation can be repeated without further changes to the resulting state beyond the first successful application. Setting a value often qualifies, whereas incrementing does not. Define retry semantics explicitly.
set_target(42); /* repeated application has the same result */Follow-up: Are all writes idempotent?
No, some trigger additional effects each time.
Scenario: A device resets under deeply nested calls.
The stack normally stores call frames and automatic objects, while dynamic allocations use an allocator region. Both may be exhausted independently. Measure representative high-water marks and examine worst-case call paths.
/* measure stack watermark during stress tests */Follow-up: Is a watermark a proof of the bound?
No, untested paths can require more stack.
Scenario: A unit test runs without the physical peripheral.
A narrow interface separates application decisions from register or driver operations. Tests can provide controlled results and record calls, while target integration tests check real hardware behavior and timing.
struct io {int (*read)(void *);void *ctx;};Follow-up: Can a fake driver prove timing correctness?
No, check timing on the target.
Scenario: A release build receives an invalid length.
Assertions express internal invariants and may be compiled out. External inputs require ordinary control-flow validation in every build. Do not place required side effects inside an assertion or rely on it for error reporting.
if(len>cap)return INVALID;assert(used<=cap);Follow-up: What does NDEBUG do?
The standard assert macro does not evaluate its argument.
Scenario: An update adds a setting to saved data.
A version distinguishes record layouts so known older records can be migrated. Decode fields explicitly, validate lengths and integrity, and assign defaults to new fields. Do not assume native struct layouts stay compatible.
if(version==1)migrate_v1();else if(version!=2)return UNSUPPORTED;Follow-up: How should an unknown newer version be handled?
Reject it or apply a documented compatibility rule.
Scenario: A time-sensitive callback records events.
Recording compact bounded events reduces critical-path work. Formatting can happen later at lower priority. Define what happens when the diagnostic buffer fills and retain meaningful event identifiers and timestamps.
record_event(EVENT_READY,tick,status);Follow-up: What metrics matter?
Recording latency, buffer capacity, event loss and decoding accuracy.
Scenario: A fake driver passes but a physical board fails.
Integration tests exercise component interactions with actual dependencies. They can reveal initialization, timing and hardware assumptions missed by unit tests. Test normal and failure cases with observable expected outcomes.
/* test initialize -> transfer -> completion on target */Follow-up: Should integration tests replace unit tests?
No, both provide complementary coverage.
Scenario: A pipeline completes many samples but results arrive late.
Throughput measures work completed per unit time; latency measures elapsed time for a particular input. Batching may increase throughput at the cost of waiting. Measure both against application requirements.
/* record input and completion timestamps per sample */Follow-up: Can high throughput coexist with missed deadlines?
Yes, individual latency may exceed a deadline.
All questions and explanations above are free. The optional DSA for Firmware course includes 28 lessons, 110 C exercises with automated tests, interactive labs and quizzes. Try two interactive lessons without an account.
Not sure where to begin? Follow the firmware interview study roadmap, review embedded C foundations or learn RTOS fundamentals.
Try Lesson 1 · Explore syllabus · Pricing and access · Free articles