FREE LEARNING RESOURCE · EMBEDDED C & FIRMWARE

Embedded C and firmware interview questions, explained

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

Choose a topic

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.

Embedded C foundations

Beginner

1. Why can a variable store only a limited range of numbers?

Scenario: Imagine an 8-bit unsigned counter that records events. What happens after 255?

Reveal explanation and example

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?

Reveal follow-up answer

Check the limit before incrementing, saturate or use a wider counter according to the requirements.

Beginner

2. What is a pointer, and why is it useful in firmware?

Scenario: A function needs to update a caller's sensor reading without returning a new value.

Reveal explanation and example

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?

Reveal follow-up answer

Dereferencing it is invalid; validate it or document a non-null contract.

Beginner

3. Why does an array need a length when passed to a function?

Scenario: A function receives a buffer of sensor samples and calculates the average.

Reveal explanation and example

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?

Reveal follow-up answer

It measures the pointer object, not the caller's array.

Beginner

4. How do you change one bit without disturbing the others?

Scenario: A simulated status byte contains independent flags. Set bit 2, clear bit 2, and test it.

Reveal explanation and example

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?

Reveal follow-up answer

No. Some registers have special write semantics or concurrent updates. Consult the device documentation.

Beginner

5. Why can sizeof a struct be larger than its members added together?

Scenario: On a typical target with 4-byte int alignment, compare a char followed by an int.

Reveal explanation and example

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?

Reveal follow-up answer

Not portably. Padding, byte order and integer sizes can differ; explicitly serialize fields.

Intermediate

6. What does volatile actually mean, and why does it not make increments atomic?

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.

Reveal explanation and example

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?

Reveal follow-up answer

Use a platform-appropriate critical section or a suitable atomic operation. Check interrupt safety and latency constraints.

Intermediate

7. What is integer promotion, and why can small integers surprise you?

Scenario: Two uint8_t operands are added before being assigned to another uint8_t.

Reveal explanation and example

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?

Reveal follow-up answer

Compare the wider result with UINT8_MAX before converting.

Beginner

8. What is the difference between a declaration and a definition?

Scenario: Two C source files need to share a configuration value.

Reveal explanation and example

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?

Reveal follow-up answer

The linker may encounter multiple external definitions of the same symbol.

Beginner

9. What is the difference between static storage and automatic storage?

Scenario: A function needs to remember how many times it has been called.

Reveal explanation and example

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?

Reveal follow-up answer

In a data or zero-initialized section, depending on initialization and the linker configuration.

Beginner

10. What does const protect in a pointer declaration?

Scenario: A parser should read incoming bytes without modifying them.

Reveal explanation and example

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?

Reveal follow-up answer

No. Placement depends on storage duration, linker configuration and target.

Beginner

11. Why can a string buffer be too small even when its characters fit?

Scenario: Store the text OK in a C string.

Reveal explanation and example

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?

Reveal follow-up answer

Characters before the first zero terminator, excluding the terminator.

Intermediate

12. Why is a signed-to-unsigned comparison surprising?

Scenario: A function compares an error value of -1 against an unsigned count.

Reveal explanation and example

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?

Reveal follow-up answer

Check the error condition first; convert only a validated nonnegative value.

Intermediate

13. What is endianness?

Scenario: Two devices exchange the number 0x1234 as two bytes.

Reveal explanation and example

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?

Reveal follow-up answer

No. It changes how that value is represented in bytes.

Intermediate

14. Why is shifting by the width of an integer invalid?

Scenario: A mask helper receives a configurable bit number.

Reveal explanation and example

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?

Reveal follow-up answer

It avoids additional restrictions associated with signed left shifts.

Intermediate

15. What is the difference between memcpy and memmove?

Scenario: Compact a buffer by moving a portion toward its beginning.

Reveal explanation and example

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?

Reveal follow-up answer

No. The caller must establish bounds.

Intermediate

16. Why can returning a pointer to a local array fail?

Scenario: A formatter returns the address of a local character buffer.

Reveal explanation and example

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?

Reveal follow-up answer

Subsequent calls can overwrite it, and concurrent calls may conflict.

Advanced

17. What is strict aliasing, and why should you care?

Scenario: A developer tries to interpret an integer's bytes by casting its address to a float pointer.

Reveal explanation and example

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?

Reveal follow-up answer

No. Copying a representation is different from converting a value.

Back to question bank start · Try the readiness check

Data structures and algorithms

Beginner

18. Why is binary search faster than checking every element?

Scenario: Find a target in a sorted table of 1,024 sensor calibration values.

Reveal explanation and example

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?

Reveal follow-up answer

It avoids overflow from adding two potentially large indices, assuming lo <= hi.

Beginner

19. What is a queue, and where would you use one?

Scenario: Sensor readings arrive faster than a display can process them for a short period.

Reveal explanation and example

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?

Reveal follow-up answer

No finite queue solves that indefinitely; reduce production, increase consumption or define a loss policy.

Beginner

20. What is a stack, and why can deep recursion be a problem?

Scenario: A recursive function traverses a tree on a device with limited stack memory.

Reveal explanation and example

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?

Reveal follow-up answer

Not always; optimization can alter frame usage. Measure or bound the actual target build.

Intermediate

21. How does a ring buffer avoid shifting data?

Scenario: A serial data stream produces bytes that another task consumes.

Reveal explanation and example

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?

Reveal follow-up answer

No. Ownership of indices, memory ordering and synchronization depend on the producer/consumer model.

Intermediate

22. Why use a fixed-size memory pool instead of repeated malloc calls?

Scenario: A device needs a bounded number of same-sized message objects.

Reveal explanation and example

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?

Reveal follow-up answer

Return a clear failure or apply a defined backpressure policy; do not silently overwrite live objects.

Intermediate

23. When is a hash table a poor choice for a small MCU?

Scenario: A configuration table holds eight keys and is searched occasionally.

Reveal explanation and example

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?

Reveal follow-up answer

When updates are rare and searches frequent, binary search can provide bounded logarithmic comparisons.

Beginner

24. Why is inserting into an array expensive?

Scenario: Insert a new item at the front of a packed list of 100 readings.

Reveal explanation and example

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?

Reveal follow-up answer

For small lists or rare insertions, simplicity and locality may outweigh the cost.

Beginner

25. What is a linked list?

Scenario: Maintain a collection whose elements need not occupy adjacent addresses.

Reveal explanation and example

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?

Reveal follow-up answer

No. Choose according to access patterns, memory overhead and allocation constraints.

Beginner

26. What does O(1) really mean?

Scenario: A lookup reads the item at a known valid array index.

Reveal explanation and example

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?

Reveal follow-up answer

No. A concrete timing bound is still needed.

Intermediate

27. How can a heap help schedule work by priority?

Scenario: A task manager must select the smallest deadline from pending jobs.

Reveal explanation and example

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?

Reveal follow-up answer

No. Only the parent-child ordering is guaranteed.

Intermediate

28. How do you choose a fixed buffer capacity?

Scenario: A producer emits bursts while a consumer occasionally pauses.

Reveal explanation and example

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?

Reveal follow-up answer

Bursts and worst-case service gaps determine peak backlog.

Intermediate

29. What is a bitmap allocator?

Scenario: Track 32 fixed slots with minimal metadata.

Reveal explanation and example

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?

Reveal follow-up answer

Four bytes for the bitmap itself, excluding other bookkeeping.

Intermediate

30. How can binary search get stuck?

Scenario: A search repeatedly chooses the same midpoint.

Reveal explanation and example

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?

Reveal follow-up answer

The interval length hi-lo decreases on every iteration until it is zero.

Intermediate

31. How would you merge two sorted streams?

Scenario: Two arrays contain time-ordered samples.

Reveal explanation and example

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?

Reveal follow-up answer

Yes, if the consumer accepts items incrementally.

Advanced

32. What is an invariant and why is it useful?

Scenario: Review a circular queue implementation for correctness.

Reveal explanation and example

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?

Reveal follow-up answer

Empty, full, transition across wraparound, and repeated insert/remove cycles.

Advanced

33. When should you avoid dynamic programming?

Scenario: A problem has a large table of overlapping subproblems but very little RAM.

Reveal explanation and example

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?

Reveal follow-up answer

No. Memory, timing predictability, complexity and energy can dominate.

Back to question bank start · Try the readiness check

Firmware reasoning and debugging

Beginner

34. What is an interrupt, and why keep its handler short?

Scenario: A periodic timer signals that a sensor sample is ready.

Reveal explanation and example

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?

Reveal follow-up answer

Not necessarily; check reentrancy, blocking behavior and the platform's interrupt-context rules.

Beginner

35. Why does a button sometimes produce multiple presses?

Scenario: A single physical press causes several rapid changes in the input signal.

Reveal explanation and example

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?

Reveal follow-up answer

Blocking may delay unrelated work; use a nonblocking state machine when responsiveness matters.

Intermediate

36. How do you design a nonblocking state machine?

Scenario: A status indicator must change every 500 ms while the main loop keeps processing messages.

Reveal explanation and example

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?

Reveal follow-up answer

Decide whether to preserve phase, catch up or skip missed intervals; each has different timing behavior.

Intermediate

37. What is a race condition?

Scenario: Two tasks use the same shared data and the result depends on which task runs first.

Reveal explanation and example

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?

Reveal follow-up answer

No. Deadlock, priority inversion, incorrect lock scope and interrupt-context restrictions still matter.

Advanced

38. Why can average execution time hide a real-time problem?

Scenario: A periodic task must finish within 1 ms. Most calls take 0.1 ms, but rare calls take 2 ms.

Reveal explanation and example

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?

Reveal follow-up answer

Instrument execution, reproduce representative load, inspect contention and bound the relevant slow paths.

Advanced

39. How can persistent settings survive interrupted writes?

Scenario: A device updates a configuration record and loses power midway.

Reveal explanation and example

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?

Reveal follow-up answer

No. It helps detect corruption, but record selection, write ordering, erase behavior and recovery must also be designed.

Intermediate

40. How do you test a function without the target board?

Scenario: A parser should correctly handle empty, valid and truncated input buffers.

Reveal explanation and example

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?

Reveal follow-up answer

Actual timing, hardware interfaces, memory limits, interrupt behavior and integration with the rest of the firmware.

Beginner

41. What is polling versus interrupts?

Scenario: A device must check whether a new sensor sample is available.

Reveal explanation and example

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?

Reveal follow-up answer

When work is periodic, response bounds are adequate and interrupt complexity is unnecessary.

Beginner

42. What is a watchdog timer?

Scenario: A program becomes unresponsive after an unexpected fault.

Reveal explanation and example

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?

Reveal follow-up answer

No. It detects selected failures and provides a recovery mechanism.

Beginner

43. Why should error codes be checked?

Scenario: A sensor read fails but the caller keeps using its previous output.

Reveal explanation and example

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?

Reveal follow-up answer

No. Permanent errors and bounded timing requirements may make retries inappropriate.

Beginner

44. How do you debug an intermittent bug?

Scenario: A test occasionally returns an incorrect measurement.

Reveal explanation and example

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?

Reveal follow-up answer

It makes the failure reproducible and supports a regression test.

Intermediate

45. What is a timeout and why is it necessary?

Scenario: A peripheral operation may never report completion.

Reveal explanation and example

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?

Reveal follow-up answer

Choose a time source that meets the timeout requirements across that mode.

Intermediate

46. What is priority inversion?

Scenario: A high-priority task waits for a resource held by a low-priority task.

Reveal explanation and example

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?

Reveal follow-up answer

No. Lock ordering and resource design still matter.

Intermediate

47. What is a deadlock?

Scenario: Two threads need the same two resources in different orders.

Reveal explanation and example

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?

Reveal follow-up answer

No. It may permit recovery, but the underlying resource protocol still needs validation.

Intermediate

48. Why does DMA need buffer ownership rules?

Scenario: A DMA controller fills a buffer while the CPU reads samples.

Reveal explanation and example

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?

Reveal follow-up answer

No. Coherency and ordering require the target's documented mechanisms.

Advanced

49. What is a fixed-point number?

Scenario: Represent a fractional value on a system using integer arithmetic.

Reveal explanation and example

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?

Reveal follow-up answer

Resolution and range compete for the available bits.

Advanced

50. What is a regression test?

Scenario: A corrected parser previously failed for an empty input.

Reveal explanation and example

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?

Reveal follow-up answer

No. It protects known behavior; new defects still require broader testing.

Back to question bank start · Try the readiness check

Embedded C: deeper practice

Beginner

51. What is the difference between an array and a pointer?

Scenario: A local array is passed to a helper.

Reveal explanation and example

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?

Reveal follow-up answer

No, it measures the pointer.

Beginner

52. Why initialize a local accumulator?

Scenario: A loop adds readings to a local sum.

Reveal explanation and example

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?

Reveal follow-up answer

Yes, to the appropriate zero value if not explicitly initialized.

Beginner

53. How does integer division handle fractions?

Scenario: A display converts 1500 ms into seconds.

Reveal explanation and example

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?

Reveal follow-up answer

Integer division by zero has undefined behavior.

Beginner

54. Why use size_t for sizes?

Scenario: A helper receives a buffer length.

Reveal explanation and example

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?

Reveal follow-up answer

No; unsigned arithmetic wraps modulo its range.

Intermediate

55. How can range checks avoid overflow?

Scenario: A parser checks offset plus length.

Reveal explanation and example

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?

Reveal follow-up answer

No, validate the underlying object separately.

Intermediate

56. What is a function pointer?

Scenario: A driver exposes a completion callback.

Reveal explanation and example

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?

Reveal follow-up answer

No, calling through an incompatible type is undefined.

Intermediate

57. Why use an enum for states?

Scenario: A parser has idle and payload states.

Reveal explanation and example

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?

Reveal follow-up answer

No; validate external inputs and handle unexpected states.

Intermediate

58. Why parenthesize macro arguments?

Scenario: A macro squares an addition expression.

Reveal explanation and example

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?

Reveal follow-up answer

A typed inline function evaluates the argument once.

Intermediate

59. Why use header guards?

Scenario: Two source dependencies include one header.

Reveal explanation and example

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 */
#endif

Follow-up: Where should external functions be defined?

Reveal follow-up answer

In one source file, with declarations in headers.

Advanced

60. What does restrict promise?

Scenario: Two buffers are processed by one helper.

Reveal explanation and example

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?

Reveal follow-up answer

No, the compiler may assume the contract holds.

Advanced

61. Why avoid unaligned typed loads?

Scenario: A packet has a 32-bit field at an odd offset.

Reveal explanation and example

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?

Reveal follow-up answer

No; it preserves the bytes.

Intermediate

62. Why use designated initializers?

Scenario: A configuration has optional fields.

Reveal explanation and example

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?

Reveal follow-up answer

It receives the appropriate zero value unless explicitly initialized.

Advanced

63. What is a flexible array member?

Scenario: A message header has variable payload size.

Reveal explanation and example

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?

Reveal follow-up answer

No, retain explicit length metadata.

Intermediate

64. What does a static assertion check?

Scenario: A protocol needs a specific integer width.

Reveal explanation and example

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?

Reveal follow-up answer

No, those are runtime values.

Advanced

65. Why can sizeof be evaluated at runtime?

Scenario: A function declares a variable-length array.

Reveal explanation and example

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?

Reveal follow-up answer

Require n <= SIZE_MAX / sizeof(int).

Intermediate

66. Why use a tagged union?

Scenario: A message holds one of two value types.

Reveal explanation and example

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?

Reveal follow-up answer

No; serialize the tag and active data explicitly.

Advanced

67. What is sequencing in C?

Scenario: An expression modifies one variable twice.

Reveal explanation and example

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?

Reveal follow-up answer

No; they change grouping.

Back to question bank start · Try the readiness check

Data structures: deeper practice

Beginner

68. How does linear search work?

Scenario: A table of device IDs is unsorted.

Reveal explanation and example

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?

Reveal follow-up answer

For small unsorted tables where sorting is unnecessary.

Intermediate

69. Why choose insertion sort for small tables?

Scenario: A short calibration table is nearly sorted.

Reveal explanation and example

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?

Reveal follow-up answer

Equal entries are not shifted past one another.

Intermediate

70. What does stable sorting preserve?

Scenario: Equal timestamps should keep arrival order.

Reveal explanation and example

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?

Reveal follow-up answer

No; stability depends on implementation.

Intermediate

71. How do you find the first matching sorted element?

Scenario: A table contains duplicate values.

Reveal explanation and example

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?

Reveal follow-up answer

The result is its insertion position; check equality separately.

Beginner

72. What is a deque?

Scenario: A work list needs operations at both ends.

Reveal explanation and example

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?

Reveal follow-up answer

Not in a simple array-backed deque.

Intermediate

73. How does a monotonic queue track a maximum?

Scenario: A rolling maximum is needed for recent samples.

Reveal explanation and example

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?

Reveal follow-up answer

Indices or timestamps to identify expired entries.

Intermediate

74. How should a full history buffer behave?

Scenario: Samples arrive after capacity is reached.

Reveal explanation and example

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?

Reveal follow-up answer

No, ownership still needs coordination.

Intermediate

75. How does separate chaining resolve collisions?

Scenario: Two configuration keys have equal hashes.

Reveal explanation and example

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?

Reveal follow-up answer

A single long chain produces linear lookup.

Advanced

76. Why use tombstones in open addressing?

Scenario: A lookup fails after a preceding key is deleted.

Reveal explanation and example

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?

Reveal follow-up answer

Searches slow down; rebuild using a bounded policy.

Intermediate

77. What is an adjacency list?

Scenario: A dependency tool represents modules as vertices.

Reveal explanation and example

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?

Reveal follow-up answer

For small dense graphs or frequent direct adjacency tests.

Intermediate

78. How does breadth-first search work?

Scenario: A graph needs shortest unweighted paths.

Reveal explanation and example

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?

Reveal follow-up answer

Allocate capacity for the maximum vertex count.

Advanced

79. How can topological sorting detect cycles?

Scenario: Module initialization has dependencies.

Reveal explanation and example

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?

Reveal follow-up answer

Yes, when multiple vertices have no remaining dependencies.

Intermediate

80. How does a bitset represent membership?

Scenario: A scheduler tracks 32 active slots.

Reveal explanation and example

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?

Reveal follow-up answer

No; shared updates require synchronization.

Advanced

81. How does amortized complexity differ from worst case?

Scenario: A collection sometimes grows during a deadline-sensitive task.

Reveal explanation and example

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?

Reveal follow-up answer

Worst-case latency and bounded resource use.

Intermediate

82. How do prefix sums speed interval queries?

Scenario: A sample history receives many sum queries.

Reveal explanation and example

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?

Reveal follow-up answer

Rebuilding can be expensive; consider an update-aware structure.

Advanced

83. When is a trie useful?

Scenario: A parser matches commands sharing prefixes.

Reveal explanation and example

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?

Reveal follow-up answer

Limit input length and validate character indices.

Back to question bank start · Try the readiness check

Firmware engineering: deeper practice

Beginner

84. Why separate initialization from processing?

Scenario: A module starts before configuration is loaded.

Reveal explanation and example

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?

Reveal follow-up answer

No, report it or enter a defined application state.

Intermediate

85. Why use a monotonic time source?

Scenario: The wall clock changes during a timeout.

Reveal explanation and example

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?

Reveal follow-up answer

Elapsed time is ambiguous; enforce a sampling bound.

Intermediate

86. What is cooperative scheduling?

Scenario: Several periodic jobs share an execution loop.

Reveal explanation and example

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?

Reveal follow-up answer

A runnable higher-priority task may interrupt lower-priority work.

Intermediate

87. Why avoid blocking a callback?

Scenario: A library calls user code on its event thread.

Reveal explanation and example

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?

Reveal follow-up answer

Use an explicit failure policy and record the loss.

Intermediate

88. What makes a function reentrant?

Scenario: A routine may be invoked while already active.

Reveal explanation and example

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?

Reveal follow-up answer

Not without a design preventing conflicting accesses.

Advanced

89. What does acquire-release ordering provide?

Scenario: One thread publishes initialized data to another.

Reveal explanation and example

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?

Reveal follow-up answer

An acquire load observing the published value before reading data.

Advanced

90. Why distinguish memory ordering from exclusion?

Scenario: Two tasks update a multi-field object.

Reveal explanation and example

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?

Reveal follow-up answer

Only when all participants follow a correct protocol.

Intermediate

91. What is a bounded retry policy?

Scenario: A peripheral sometimes reports busy.

Reveal explanation and example

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?

Reveal follow-up answer

The resource may need time to become available.

Intermediate

92. What is the distinction between checksums and correction?

Scenario: A receiver detects corrupted messages.

Reveal explanation and example

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?

Reveal follow-up answer

No, it detects accidental errors rather than authenticating.

Intermediate

93. What does idempotent mean?

Scenario: A retry delivers the same configuration command twice.

Reveal explanation and example

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?

Reveal follow-up answer

No, some trigger additional effects each time.

Advanced

94. Why distinguish stack and heap use?

Scenario: A device resets under deeply nested calls.

Reveal explanation and example

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?

Reveal follow-up answer

No, untested paths can require more stack.

Intermediate

95. Why abstract hardware access behind an interface?

Scenario: A unit test runs without the physical peripheral.

Reveal explanation and example

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?

Reveal follow-up answer

No, check timing on the target.

Advanced

96. How do assertions differ from input validation?

Scenario: A release build receives an invalid length.

Reveal explanation and example

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?

Reveal follow-up answer

The standard assert macro does not evaluate its argument.

Intermediate

97. Why version a stored configuration format?

Scenario: An update adds a setting to saved data.

Reveal explanation and example

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?

Reveal follow-up answer

Reject it or apply a documented compatibility rule.

Advanced

98. Why defer diagnostic formatting?

Scenario: A time-sensitive callback records events.

Reveal explanation and example

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?

Reveal follow-up answer

Recording latency, buffer capacity, event loss and decoding accuracy.

Advanced

99. What does an integration test verify?

Scenario: A fake driver passes but a physical board fails.

Reveal explanation and example

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?

Reveal follow-up answer

No, both provide complementary coverage.

Advanced

100. Why distinguish latency and throughput?

Scenario: A pipeline completes many samples but results arrive late.

Reveal explanation and example

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?

Reveal follow-up answer

Yes, individual latency may exceed a deadline.

Back to question bank start · Try the readiness check

Want structured practice?

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