Embedded C Interview Questions and Answers: 22 with Tested Code
Model answers to 22 embedded C questions asked of freshers and automotive engineers: volatile and what it does not guarantee, const and static, memory sections, struct padding, register bit masks, integer promotion, ISRs, ring buffers, watchdogs and MISRA C. Every snippet was compiled with -Wall -Wextra and run, and the real output is shown.

The most common embedded C interview questions are about how C meets hardware: what volatile really guarantees, where each variable sits in flash and RAM, how to change one register field without breaking the others, and what goes wrong when an interrupt and the main loop share data. Interviewers also probe C's quiet traps, such as integer promotion and macro side effects.
In short
- This guide covers 22 topics that embedded C interviews for freshers and automotive roles are built around: volatile, const and static, memory sections, struct padding, bit masks on registers, integer promotion, ISRs and shared data, ring buffers, watchdogs and MISRA C.
- Every snippet was compiled with
-Wall -Wextraand run on 17 Nov 2026, and the output shown is the real output. Some were also compiled for an Arm Cortex-M4 to show the machine code.- Two results surprise most candidates. Without
volatile, clang at-O2deleted a wait-for-flag loop completely. And avolatilecounter shared by two threads lost up to 714,596 of 2,000,000 increments.- Answers cite the C11 standard (draft N1570) by clause, plus ST and Arm vendor files.
Below are model answers to 22 such questions. Each starts with the short answer you would give in the room, then the proof: a small program, its real output and the C standard clause behind it.
For microcontroller, UART/I2C/SPI/CAN and RTOS questions, read our embedded interview questions guide. For the automotive software stack, read the AUTOSAR interview questions.
How were these answers tested?
- Host:
gcc -std=c11 -Wall -Wextra -O2on an arm64 Mac, wheregccis Apple clang 15.0.0. A build script also runs each program at-O0and checks the output matches. - Cortex-M4:
clang --target=thumbv7em-none-eabi -mcpu=cortex-m4 -ffreestanding -O2 -c, disassembled withobjdump. - Undefined behaviour was confirmed with clang's UndefinedBehaviorSanitizer (
-fsanitize=undefined).
Type sizes and struct layouts are implementation-defined. Both targets here have a 4-byte int and are little-endian, like most 32-bit Arm microcontrollers. An 8-bit AVR or a 16-bit MSP430 differs.
Embedded C basics
1. What is the difference between C and Embedded C?
Embedded C is not a separate language. It is standard C written for a microcontroller, usually as a freestanding program: no operating system, execution starts at a reset handler, only a few standard headers are guaranteed, and the code talks to hardware through memory-mapped registers.
C11 clause 4p6 defines hosted implementations, with the full library, and freestanding ones, which only have to support <float.h>, <iso646.h>, <limits.h>, <stdalign.h>, <stdarg.h>, <stdbool.h>, <stddef.h>, <stdint.h> and <stdnoreturn.h>. That is why printf and malloc are often missing or replaced on small targets.
There is also an ISO document literally called "Embedded C": ISO/IEC TR 18037:2008, a technical report adding fixed-point types, named address spaces and I/O hardware addressing. In job ads, "Embedded C" simply means ISO C plus a vendor compiler and the chip's register headers.
Follow-up: "Is Arduino code Embedded C?" Strictly, no. The build joins the .ino files into one .cpp file, so it is compiled as C++, though C-style code works fine.
volatile, const and static questions
2. What does the volatile keyword do?
volatile tells the compiler that an object can change, or be read, by something it cannot see: hardware, an interrupt handler or another core. So every read and write in the source must really happen, and none may be cached in a register or removed. Use it for memory-mapped registers and for flags shared with an ISR.
C11 6.7.3p7 requires volatile accesses to be "evaluated strictly according to the rules of the abstract machine", and footnote 134 names the two classic uses: memory-mapped I/O ports and objects touched by an interrupting function. Here is the proof, with two functions waiting for a flag set by an ISR:
uint32_t data_ready_plain; /* set by an ISR, but NOT volatile */
volatile uint32_t data_ready; /* set by an ISR, volatile */
void wait_plain(void) { while (data_ready_plain == 0u) { } }
void wait_volatile(void) { while (data_ready == 0u) { } }
Compiled for Cortex-M4 at -O2, this is the machine code:
00000000 <wait_plain>:
0: bx lr
00000002 <wait_volatile>:
2: movw r0, #0
6: movt r0, #0
a: b 0x18 <wait_volatile+0x16> @ imm = #10
c: ldr r1, [r0]
e: cmp r1, #0
10: it ne
12: bxne lr
14: ldr r1, [r0]
16: cbnz r1, 0x22 <wait_volatile+0x20> @ imm = #8
18: ldr r1, [r0]
1a: cbnz r1, 0x22 <wait_volatile+0x20> @ imm = #4
1c: ldr r1, [r0]
1e: cmp r1, #0
20: beq 0xc <wait_volatile+0xa> @ imm = #-24
22: bx lr
wait_plain became a single bx lr (return): the loop is gone and the function no longer waits. Nothing in the loop changes the flag, and C11 6.8.5p6 lets the compiler assume a loop with no I/O, volatile or atomic access will end. wait_volatile reloads the flag (ldr r1, [r0]) on every pass, even after clang unrolled it four times. Other compilers may turn the plain version into an endless loop instead. Either way, it no longer does what you wrote.
3. What does volatile NOT guarantee?
volatile does not make an operation atomic, and it does not order ordinary (non-volatile) memory accesses around it. count++ on a volatile variable is still three steps (load, add, store), so an interrupt or another thread can step in halfway. Protect shared read-modify-write operations with a critical section, a C11 atomic or an RTOS mutex.
The test below runs two threads. Each adds 1,000,000 to a volatile counter and to a C11 atomic_int:
volatile int vcount = 0; /* volatile: every access really happens */
atomic_int acount = 0; /* C11 atomic: each ++ is indivisible */
static void *worker(void *arg)
{
(void)arg;
for (int i = 0; i < N; i++) {
vcount++; /* load, add, store: can interleave */
atomic_fetch_add(&acount, 1); /* one atomic read-modify-write */
}
return NULL;
}
Output of five runs:
expected 2000000, volatile got 1361734, atomic got 2000000
expected 2000000, volatile got 1285404, atomic got 2000000
expected 2000000, volatile got 1667096, atomic got 2000000
expected 2000000, volatile got 1720209, atomic got 2000000
expected 2000000, volatile got 1798897, atomic got 2000000
The volatile counter lost between 201,103 and 714,596 increments, a different number each run. The atomic counter was exact every time. On a single-core microcontroller the same thing happens when an ISR changes a variable between the main loop's load and store.
On ordering, GCC's manual is blunt: "You cannot use a volatile object as a memory barrier", because non-volatile accesses can move around it. The Linux kernel's volatile considered harmful guide agrees that volatile suppresses optimisation, while concurrency needs locks and barriers.
Follow-up: "What can a signal handler safely write?" A volatile sig_atomic_t or a lock-free atomic; anything else is undefined behaviour (C11 7.14.1.1p5). The same idea applies to ISRs.
4. What is the difference between const int *p, int *const p and const volatile?
Read the declaration from right to left. const uint8_t *p is a pointer to const data: you can move p but cannot write through it. uint8_t *const p is a const pointer: it always points at the same place, but you can change the data there. const uint8_t *const p locks both.
static const uint16_t crc_table[4] = { 0x0000u, 0x1021u, 0x2042u, 0x3063u }; /* goes to .rodata (flash) */
int main(void)
{
uint8_t a = 10u, b = 20u;
const uint8_t *p1 = &a; /* pointer to const: *p1 is read-only, p1 can move */
uint8_t *const p2 = &a; /* const pointer: p2 is fixed, *p2 can be written */
const uint8_t *const p3 = &a; /* both fixed */
p1 = &b; /* OK */
*p2 = 15u; /* OK: a is now 15 */
printf("*p1=%u *p2=%u *p3=%u crc_table[1]=0x%04X\n",
(unsigned)*p1, (unsigned)*p2, (unsigned)*p3, (unsigned)crc_table[1]);
return 0;
}
*p1=20 *p2=15 *p3=15 crc_table[1]=0x1021
Break the rules and clang stops you:
void bad(uint8_t *buf)
{
const uint8_t *p1 = buf;
uint8_t *const p2 = buf;
*p1 = 1u; /* error: writing through a pointer to const */
p2 = buf + 1; /* error: moving a const pointer */
}
const_err.c:7:9: error: read-only variable is not assignable
*p1 = 1u; /* error: writing through a pointer to const */
~~~ ^
const_err.c:8:8: error: cannot assign to variable 'p2' with const-qualified type 'uint8_t *const' (aka 'unsigned char *const')
p2 = buf + 1; /* error: moving a const pointer */
~~ ^
const_err.c:6:20: note: variable 'p2' declared const here
uint8_t *const p2 = buf;
~~~~~~~~~~~~~~~^~~~~~~~
2 errors generated.
- Where const data lives. C11 footnote 132 lets a
constobject go in read-only storage, which on a microcontroller means flash, not scarce RAM (question 6 shows it in.rodata). - const volatile. A read-only hardware status register is
const volatile: your code must not write it (const), but the hardware changes it (volatile). Arm's CMSIS core header, which ST's device headers build on, uses the same idea: in C its__I(read-only) and__IO(read/write) register qualifiers expand tovolatile constandvolatile.
Casting const away and writing to an object defined const is undefined behaviour (C11 6.7.3p6); on a microcontroller the write may hit flash and fail or fault.
5. What are the uses of the static keyword in C?
static does two different jobs. On a local variable, it gives static storage duration: the variable is initialised once and keeps its value between calls. On a file-scope variable or function, it gives internal linkage (C11 6.2.2p3): the name is private to that .c file, so two files can use the same name without a clash.
/* static_a.c */
static int count = 0; /* internal linkage: private to static_a.c */
static void tick(void) { count++; } /* private helper, no clash with static_b.c */
static int next_id(void)
{
static int id = 100; /* static local: initialised once, lives forever */
return ++id;
}
/* static_b.c: the same names, no linker error */
static int count = 0;
static void tick(void) { count++; }
void b_tick(void) { tick(); }
int b_count(void) { return count; }
Built together as gcc static_a.c static_b.c, with no linker error:
a count=3, b count=1, ids 101 102
Each file kept its own count, and next_id() remembered its value. Make every module-private function and variable static: it keeps the global namespace small and lets the compiler inline or drop code. A static local without an initialiser starts at zero (C11 6.7.9p10) and lives in .data or .bss, never on the stack.
Memory layout questions
6. Where do .text, .data, .bss, the stack and the heap live?
Code (.text) and const data (.rodata) stay in flash. Initialised globals and statics (.data) live in RAM, but their starting values are stored in flash and copied to RAM at reset. Zero-initialised globals (.bss) live in RAM and are cleared at reset. Local variables go on the stack (or in registers), and malloc uses the heap.
uint32_t boot_count = 7u; /* initialised, non-zero -> .data */
uint32_t rx_errors; /* no initialiser, zero -> .bss */
static uint8_t rx_buf[256]; /* zero-filled array -> .bss */
const uint16_t adc_lut[8] = {0, 585, 1170, 1755, 2340, 2925, 3510, 4095}; /* -> .rodata */
uint32_t sum_lut(size_t n) /* code -> .text */
{
uint32_t s = 0u; /* local: register/stack at run time */
for (size_t i = 0u; i < n; i++) { s += adc_lut[i] + rx_buf[i]; }
return s + boot_count + rx_errors;
}
void rx_store(size_t i, uint8_t b) { rx_buf[i & 255u] = b; } /* written by the UART ISR */
Compiled for Cortex-M4, the object file's sections and symbols are:
Sections (objdump -h):
2 .text 000000de 00000000 TEXT
6 .data 00000004 00000000 DATA
7 .rodata 00000010 00000000 DATA
8 .bss 00000104 00000000 BSS
Symbols (nm -S):
00000000 00000010 R adc_lut
00000000 00000004 D boot_count
00000000 00000100 b rx_buf
00000000 000000d0 T sum_lut
000000d0 0000000e T rx_store
00000100 00000004 B rx_errors
Every object landed where predicted: boot_count in .data (4 bytes), rx_errors and rx_buf in .bss (4 + 256 = 260 bytes, 0x104), adc_lut in .rodata (8 × 2 = 16 bytes). The lower-case b marks rx_buf as a local symbol because it is static. .bss costs RAM but no flash; startup code only needs its size to clear it.
ST's STM32F407 reset handler sets the stack pointer to _estack (top of RAM), calls SystemInit, copies .data from flash to SRAM, zero-fills .bss and only then calls main(). That is why an uninitialised global starts at zero.
7. Why do embedded teams avoid malloc?
Dynamic allocation makes timing and memory use hard to predict. malloc can take a different time on each call, can fail at run time when the heap is fragmented into small holes, and brings the risk of leaks and use-after-free. A device that must run for years cannot afford that. Most firmware allocates everything statically, or only once at start-up.
MISRA C:2012 makes this a Required rule. Rule 21.3 says the memory allocation and deallocation functions of <stdlib.h> shall not be used. That covers malloc, calloc, realloc, aligned_alloc and free. Fixed-size pools and ring buffers (question 19) are the usual replacements.
8. What is a dangling pointer, and why doesn't firmware just segfault?
A dangling pointer still holds the address of memory that is no longer valid: a local variable whose function has returned, or a block that has been freed. Using it is undefined behaviour. On a PC you might get a segmentation fault. On a microcontroller without a memory protection unit there is usually no fault at all. The write silently corrupts whatever now uses that RAM, often the stack.
uint8_t *make_frame(void)
{
uint8_t frame[8] = {0};
return frame; /* frame dies when the function returns */
}
dangling.c:6:12: warning: address of stack memory associated with local variable 'frame' returned [-Wreturn-stack-address]
return frame; /* frame dies when the function returns */
^~~~~
1 warning generated.
Clang catches this simple case, so build with -Werror. In general: return data through a buffer the caller owns, set pointers to NULL after freeing, and never keep a local's address after its function returns. On parts with an MPU, a guard region below the stack turns silent overflow into a catchable fault.
9. What is structure padding, and how do you reduce it?
The compiler puts unused bytes between struct members so that each member sits at an address suited to its alignment, usually its own size for basic types. The C standard allows padding anywhere except before the first member (C11 6.7.2.1p15), and at the end. To reduce it, order members from largest to smallest. Use packed only when a layout must match a wire format.
struct msg_bad { /* members in "natural" order */
uint8_t id;
uint32_t timestamp;
uint8_t flags;
uint16_t value;
};
struct msg_good { /* largest first */
uint32_t timestamp;
uint16_t value;
uint8_t id;
uint8_t flags;
};
struct __attribute__((packed)) msg_packed { /* GCC/Clang extension */
uint8_t id;
uint32_t timestamp;
uint8_t flags;
uint16_t value;
};
/* Fail the build if a layout ever changes (C11 _Static_assert) */
_Static_assert(sizeof(struct msg_good) == 8u, "msg_good must stay 8 bytes");
struct msg_bad: sizeof = 12
id offset 0 size 1
timestamp offset 4 size 4
flags offset 8 size 1
value offset 10 size 2
struct msg_good: sizeof = 8
timestamp offset 0 size 4
value offset 4 size 2
id offset 6 size 1
flags offset 7 size 1
struct msg_packed: sizeof = 8
id offset 0 size 1
timestamp offset 1 size 4
flags offset 5 size 1
value offset 6 size 2
A second file asserting every offset with _Static_assert compiled cleanly for Cortex-M4, so the layout is identical there. Reordering reached 8 bytes without packing. packed is a GCC/Clang extension that gives members "the smallest possible alignment" (GCC manual), which puts timestamp at offset 1: slower byte-wise access, and a pointer to it can fault on cores without unaligned access.
Follow-up: "How do you send a struct over CAN or UART?" Don't memcpy it. Serialise each field with shifts (question 10), so padding and byte order stop mattering.
10. What is endianness, and how do you detect it in C?
Endianness is the order in which a multi-byte value's bytes are stored in memory. Little-endian puts the least significant byte at the lowest address; big-endian puts the most significant byte first. To detect it, store a known value and look at its first byte. To avoid depending on it, build byte streams with shifts, which give the same result on any CPU.
static int is_little_endian(void)
{
const uint32_t probe = 1u;
uint8_t first;
memcpy(&first, &probe, 1); /* look at the byte at the lowest address */
return first == 1u;
}
/* Byte-order-independent: works the same on any CPU */
static void put_be32(uint8_t out[4], uint32_t v)
{
out[0] = (uint8_t)(v >> 24);
out[1] = (uint8_t)(v >> 16);
out[2] = (uint8_t)(v >> 8);
out[3] = (uint8_t)v;
}
host is little-endian
in memory : 78 56 34 12
put_be32 : 12 34 56 78
The host stored 0x12345678 as 78 56 34 12: little-endian. put_be32 produced big-endian bytes regardless, because shifts act on values, not memory layout. C leaves byte order implementation-defined (C11 6.2.6.1p2).
Follow-up: "Can you use a union instead?" In C (unlike C++) reading a different union member than the one last written is defined: C11 footnote 95 calls it "type punning" and says the bytes are reinterpreted. memcpy into a byte is equally clear, and compilers optimise it away.
Bit manipulation and integer questions
11. How do you set, clear, toggle and test a bit?
Set a bit with OR, clear it with AND of the inverted mask, toggle it with XOR, and test it by shifting right and masking with 1. Build masks from an unsigned constant (1UL << n). With a plain 1, which is a signed int, shifting into bit 31 is undefined behaviour (question 14).
#define BIT(n) (1UL << (n))
int main(void)
{
uint32_t reg = 0x00000000UL;
reg |= BIT(5); /* set bit 5 -> 0x00000020 */
reg |= BIT(31); /* set bit 31 -> 0x80000020 */
reg ^= BIT(0); /* toggle bit 0 -> 0x80000021 */
reg &= ~BIT(5); /* clear bit 5 -> 0x80000001 */
unsigned b31 = (unsigned)((reg >> 31) & 1UL); /* test bit 31 */
unsigned b5 = (unsigned)((reg >> 5) & 1UL); /* test bit 5 */
printf("reg=0x%08lX bit31=%u bit5=%u\n", (unsigned long)reg, b31, b5);
return 0;
}
reg=0x80000001 bit31=1 bit5=0
12. How do you change one field in a register without touching the others?
Read the register once into a local, clear the field with an inverted mask, OR in the new value shifted into place, and write it back once. If an ISR can write the same register, protect that read-modify-write, or use the chip's set/reset register, which needs no read.
The example uses ST's STM32F4 GPIO layout. MODER has a 2-bit mode field per pin (00 input, 01 output, 10 alternate function, 11 analog), so pin 5 is bits 11:10 (mask 0x00000C00). Writing 1 to bit n of the write-only BSRR sets pin n; bit n + 16 resets it. The registers are simulated in RAM so this runs on a PC.
#define GPIO_MODE_OUTPUT 1UL /* 00 in, 01 out, 10 AF, 11 analog */
#define FIELD_MASK(w, pos) (((1UL << (w)) - 1UL) << (pos))
static void pin_mode(gpio_t *port, unsigned pin, uint32_t mode)
{
uint32_t v = port->MODER; /* 1 read */
v &= ~FIELD_MASK(2u, pin * 2u); /* clear the 2-bit field */
v |= (mode << (pin * 2u)); /* insert new value */
port->MODER = v; /* 1 write */
}
pin_mode(GPIOA, 5u, GPIO_MODE_OUTPUT); /* PA5 -> output */
GPIOA->BSRR = (1UL << 5); /* set PA5: no read-modify-write */
GPIOA->BSRR = (1UL << (5 + 16)); /* reset PA5: bits 16-31 reset */
MODER before: 0x00000F00
MODER after : 0x00000700
ODR after BSRR set : 0x00000020
ODR after BSRR reset: 0x00000000
From 0x00000F00 the update gives 0x00000700: pin 5 becomes 01 and pin 4's 11 is untouched. BSRR exists because ODR |= (1u << 5) is a read-modify-write: if an ISR changes another pin between the read and the write, its change is lost. A BSRR write cannot lose anything, since zero bits do nothing.
13. What are the integer promotion traps in C?
Before most arithmetic, C converts types narrower than int (uint8_t, uint16_t, char) to int: integer promotion (C11 6.3.1.1p2). And when signed meets unsigned of the same rank, the signed operand becomes unsigned (6.3.1.8). Both rules produce results that look wrong until you know them.
uint8_t x = 0x0Fu;
printf("1) ~x == 0xF0 ? %s (~x is the int 0x%X)\n",
(~x == 0xF0) ? "yes" : "no", (unsigned)~x);
uint8_t c = 200u;
uint8_t sum8 = (uint8_t)(c + 100u); /* c + 100 is computed as int: 300 */
printf("2) c + 100 = %d as int, %u after storing in uint8_t\n", c + 100, (unsigned)sum8);
volatile uint16_t a = 65535u, b = 65535u;
uint32_t good = (uint32_t)a * b; /* unsigned 32-bit multiply */
uint32_t bad = a * b; /* both promoted to int: overflow */
printf("3) (uint32_t)a*b = %lu, a*b = %lu\n", (unsigned long)good, (unsigned long)bad);
int i = -1;
printf("4) -1 < sizeof(int) ? %s\n", (i < sizeof(int)) ? "yes" : "no");
1) ~x == 0xF0 ? no (~x is the int 0xFFFFFFF0)
2) c + 100 = 300 as int, 44 after storing in uint8_t
3) (uint32_t)a*b = 4294836225, a*b = 4294836225
4) -1 < sizeof(int) ? no
~xis an int.xis promoted to the int0x0000000Fbefore~, giving0xFFFFFFF0, which is not0xF0. Cast back:(uint8_t)~x == 0xF0.- Arithmetic happens in int.
c + 100is 300. Storing it back inuint8_tkeeps 300 mod 256 = 44. - uint16_t × uint16_t can overflow. Both become signed ints, and 65,535 × 65,535 = 4,294,836,225 exceeds the int maximum of 2,147,483,647: signed overflow, undefined behaviour. It printed the "right" number by luck. UndefinedBehaviorSanitizer catches it:
1) ~x == 0xF0 ? no (~x is the int 0xFFFFFFF0)
2) c + 100 = 300 as int, 44 after storing in uint8_t
3) (uint32_t)a*b = 4294836225, a*b = 4294836225
4) -1 < sizeof(int) ? no
promotion.c:17:23: runtime error: signed integer overflow: 65535 * 65535 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior promotion.c:17:23 in
Fix: cast one operand first, (uint32_t)a * b, so the multiply is unsigned.
- Signed vs unsigned comparison.
sizeofgives an unsigned type, so-1is converted to a huge unsigned value and-1 < sizeof(int)is false.-Wextrawarns about exactly this:
promotion.c:21:45: warning: comparison of integers of different signs: 'int' and 'unsigned long' [-Wsign-compare]
printf("4) -1 < sizeof(int) ? %s\n", (i < sizeof(int)) ? "yes" : "no");
~ ^ ~~~~~~~~~~~
1 warning generated.
On 8-bit and 16-bit microcontrollers int is usually 16 bits, so these results change again. That is why MISRA C has its own "essential type" rules (question 22).
14. Why is 1 << 31 a bug?
The constant 1 has type int. With a 32-bit int, 1 << 31 gives 231, which cannot be represented in an int. C11 6.5.7p4 makes that undefined behaviour. Shifting by a negative amount, or by at least the width of the type, is undefined too (6.5.7p3). Write 1u << 31 or 1UL << n.
volatile int n = 31;
int mask = 1 << n; /* 1 is an int: 1 << 31 overflows a 32-bit int */
mask = -2147483648
shift_ub.c:6:18: runtime error: left shift of 1 by 31 places cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior shift_ub.c:6:18 in
It printed a plausible -2147483648, which is the danger: it works until a new compiler or optimisation level exploits the undefined behaviour. That is why ST's headers write masks as 0x1UL << n.
Macros, inline functions and function pointers
15. What is the difference between a macro and an inline function?
A function-like macro is text substitution by the preprocessor. It has no types, and its arguments are pasted in, so an argument with a side effect such as i++ can run twice. A static inline function is a real function: arguments are type-checked and evaluated exactly once, and the compiler can still inline it as fast as a macro. Prefer inline functions; keep macros for constants, conditional compilation and register definitions.
#define MAX(a, b) ((a) > (b) ? (a) : (b)) /* arguments may be evaluated twice */
static inline int max_i(int a, int b) { return a > b ? a : b; } /* each argument once */
#define SWAP_INT(x, y) do { int t_ = (x); (x) = (y); (y) = t_; } while (0)
int i = 5, j = 5;
int m1 = MAX(i++, 3); /* expands to ((i++) > (3) ? (i++) : (3)) */
int m2 = max_i(j++, 3);
printf("MAX: result %d, i is now %d\n", m1, i);
printf("max_i: result %d, j is now %d\n", m2, j);
int p = 1, q = 2;
if (p < q)
SWAP_INT(p, q); /* do { } while (0) makes this one statement */
else
puts("never");
printf("after swap: p=%d q=%d\n", p, q);
MAX: result 6, i is now 7
max_i: result 5, j is now 6
after swap: p=2 q=1
MAX(i++, 3) incremented i twice and returned 6, while max_i(j++, 3) behaved as written. Note that C11 6.7.4p6 only says inline "suggests" a fast call. The compiler decides.
Follow-up: "Why wrap a multi-statement macro in do { } while (0)?" So that it behaves like one statement. With plain braces, the semicolon after the macro ends the if, and the else no longer compiles:
#define SWAP_BAD(x, y) { int t_ = (x); (x) = (y); (y) = t_; }
void f(int p, int q)
{
if (p < q)
SWAP_BAD(p, q); /* the ';' after '}' ends the if, so ... */
else /* ... this else has no if */
p = 0;
}
macro_err.c:8:5: error: expected expression
else /* ... this else has no if */
^
1 error generated.
16. How are function pointers used in embedded code?
A function pointer holds the address of a function, so the code to run can be chosen at run time. In firmware you see three uses: the interrupt vector table (an array of handler addresses), callbacks that let a driver notify the application without knowing about it, and dispatch tables that map a command or state to its handler.
typedef int (*cmd_fn)(int arg);
static int cmd_led(int arg) { printf(" LED %s\n", arg ? "on" : "off"); return 0; }
static int cmd_pwm(int arg) { printf(" PWM duty %d%%\n", arg); return 0; }
static int cmd_rst(int arg) { (void)arg; printf(" soft reset requested\n"); return 0; }
typedef struct { const char *name; cmd_fn fn; } cmd_entry;
static const cmd_entry cmd_table[] = { /* const: table lives in flash */
{ "led", cmd_led },
{ "pwm", cmd_pwm },
{ "rst", cmd_rst },
};
static int dispatch(const char *name, int arg)
{
for (size_t k = 0; k < sizeof cmd_table / sizeof cmd_table[0]; k++) {
if (strcmp(cmd_table[k].name, name) == 0) {
return cmd_table[k].fn(arg); /* call through the pointer */
}
}
return -1; /* unknown command */
}
/* Callback registration: a driver calls back into application code */
typedef void (*button_cb)(unsigned pin);
static button_cb on_press = NULL;
static void button_register(button_cb cb) { on_press = cb; }
static void button_isr_sim(unsigned pin) { if (on_press != NULL) { on_press(pin); } }
static void app_on_press(unsigned pin) { printf(" button on pin %u pressed\n", pin); }
dispatch("led", 1);
dispatch("pwm", 40);
printf(" unknown -> %d\n", dispatch("xyz", 0));
button_register(app_on_press);
button_isr_sim(13u);
LED on
PWM duty 40%
unknown -> -1
button on pin 13 pressed
soft reset requested
Declaring the table const keeps it in flash, where a stray pointer cannot overwrite it. Always check a callback for NULL before calling it, as button_isr_sim does. A corrupted function pointer jumps to a random address, and that is one of the hardest crashes to trace.
Interrupt (ISR) questions
17. What are the rules for writing an ISR?
Keep it short and never block. An ISR should acknowledge the interrupt, move data into a buffer or set a flag, and return, leaving the heavy work to the main loop or a task. It takes no arguments, returns nothing, and must never wait for something only the interrupted code can release.
- No blocking: no delays, busy-waits or mutex waits. The official FreeRTOS book says never to call a FreeRTOS function without "FromISR" in its name from an ISR.
- No slow or non-reentrant calls such as
printformalloc. - Shared variables are volatile, and multi-byte or read-modify-write access is protected (question 18).
- Clear the interrupt flag, or on many peripherals the interrupt fires again on return and the main loop seems frozen.
Follow-up: "What makes a function reentrant?" It can be interrupted and safely called again before the first call ends: only locals and arguments, no static state. strtok, with its hidden static pointer, is the classic counter-example.
18. How do you protect data shared between an ISR and the main loop?
Make the shared variable volatile, then make every access that is not a single load or store indivisible. Usually that means a very short critical section: save the interrupt mask, disable interrupts, access the data, restore the mask. For a counter only an ISR writes, you can instead re-read until two reads agree.
The classic bug: a 64-bit tick counter on a 32-bit MCU needs two loads, and a timer ISR between them mixes halves from different moments. This program injects the interrupt at exactly that point:
uint64_t read_naive(void)
{
uint32_t lo = ticks_lo;
maybe_interrupt(); /* ISR fires here: lo is stale */
uint32_t hi = ticks_hi;
return ((uint64_t)hi << 32) | lo;
}
uint64_t read_critical(void) /* fix 1: short critical section */
{
disable_irq();
uint32_t lo = ticks_lo;
maybe_interrupt(); /* held off until enable_irq() */
uint32_t hi = ticks_hi;
enable_irq();
return ((uint64_t)hi << 32) | lo;
}
uint64_t read_retry(void) /* fix 2: re-read until stable */
{
uint32_t hi, lo;
do {
hi = ticks_hi;
lo = ticks_lo;
maybe_interrupt();
} while (hi != ticks_hi);
return ((uint64_t)hi << 32) | lo;
}
naive : 0x00000001FFFFFFFF (counter is now 0x0000000100000000)
critical : 0x00000000FFFFFFFF (counter is now 0x0000000100000000)
retry : 0x0000000100000000 (counter is now 0x0000000100000000)
The naive read returned 0x1_FFFFFFFF when the true count was 0x1_00000000, wrong by
The critical-section read returned the consistent value from before the tick, and the retry read the one after it. Both are correct. On a real Cortex-M4 the critical section looks like this:
static inline uint32_t irq_save(void)
{
uint32_t primask;
__asm volatile ("mrs %0, primask\n\tcpsid i" : "=r"(primask) :: "memory");
return primask; /* remember if IRQs were already off */
}
static inline void irq_restore(uint32_t primask)
{
__asm volatile ("msr primask, %0" :: "r"(primask) : "memory");
}
volatile uint32_t ticks_lo, ticks_hi;
uint64_t ticks_read(void)
{
uint32_t s = irq_save();
uint64_t t = ((uint64_t)ticks_hi << 32) | ticks_lo;
irq_restore(s);
return t;
}
00000000 <ticks_read>:
0: movw r0, #0
4: mrs r2, primask
8: cpsid i
a: movt r0, #0
e: ldr r1, [r0]
10: movw r0, #0
14: movt r0, #0
18: ldr r0, [r0]
1a: msr primask, r2
1e: bx lr
mrs r2, primask saves the mask, cpsid i disables interrupts, two ldrs read both halves, and msr primask, r2 restores the mask. In projects you call CMSIS __get_PRIMASK(), __disable_irq() and __set_PRIMASK(), which Arm documents as these instructions. Restoring the saved mask, instead of blindly re-enabling, keeps the code correct if interrupts were already off.
19. How do you implement a circular (ring) buffer for UART data?
Use a fixed array with two indices. The ISR (the producer) writes at head, and the main loop (the consumer) reads at tail. With exactly one producer and one consumer, each index is written by only one side, so no lock is needed on a single-core MCU. If the size is a power of two, a bitwise AND replaces the slow modulo.
#define RB_SIZE 8u /* must be a power of two */
_Static_assert((RB_SIZE & (RB_SIZE - 1u)) == 0u, "RB_SIZE must be a power of two");
typedef struct {
uint8_t buf[RB_SIZE];
volatile uint8_t head; /* written only by the producer (ISR) */
volatile uint8_t tail; /* written only by the consumer (main) */
} ring_t;
static unsigned rb_count(const ring_t *r) { return (uint8_t)(r->head - r->tail); }
static int rb_put(ring_t *r, uint8_t byte) /* call from the UART RX ISR */
{
if (rb_count(r) == RB_SIZE) { return 0; } /* full: drop, count an overrun */
r->buf[r->head & (RB_SIZE - 1u)] = byte; /* write data first ... */
r->head = (uint8_t)(r->head + 1u); /* ... then publish it */
return 1;
}
static int rb_get(ring_t *r, uint8_t *byte) /* call from the main loop */
{
if (r->head == r->tail) { return 0; } /* empty */
*byte = r->buf[r->tail & (RB_SIZE - 1u)];
r->tail = (uint8_t)(r->tail + 1u);
return 1;
}
put 10 bytes: 8 accepted, 2 dropped, count=8
get 3: ABC count=5
put xyz, drain: DEFGHxyz head=11 tail=11
1000 put/get pairs across index wrap: 0 errors, head=243 tail=243
It accepted 8 of 10 bytes (count the 2 overruns), returned data in order, and passed 1,000 more put/get pairs across the 8-bit index wrap (255 → 0) with no errors. The indices run freely and are masked only when used; since 256 is a multiple of 8, the count stays right at the wrap:
That separates full (8) from empty (0) without wasting a slot. The Linux kernel's circular-buffer guide uses the same power-of-two trick and adds that, without a shared lock, producer and consumer need memory barriers: question 3's point again.
Watchdog and MISRA questions
20. What is a watchdog timer, and where should you kick it?
A watchdog is a hardware down-counter that resets the microcontroller when it reaches zero. Healthy firmware reloads ("kicks") it in time, so a hang ends in a clean reset instead of a frozen device. Kick it from one place in the main loop, only after every critical task has checked in. Never kick it from a timer ISR, which keeps running when the main code is stuck.
The STM32F4 independent watchdog (IWDG) runs from the internal LSI clock, so it survives a main-clock failure. ST's HAL starts it with key 0xCCCC and reloads it with 0xAAAA; once started it cannot be disabled. This simulation services a 100 ms watchdog every 10 ms, and one task hangs at 200 ms:
#define TASK_COMMS (1u << 0)
#define TASK_CONTROL (1u << 1)
#define TASK_ALL (TASK_COMMS | TASK_CONTROL)
static volatile uint32_t alive; /* each task sets its bit when healthy */
static void watchdog_service(void) /* called once per 10 ms loop */
{
if ((alive & TASK_ALL) == TASK_ALL) { /* kick only if EVERY task checked in */
IWDG_KR_write(KEY_RELOAD);
alive = 0u;
}
}
t= 0 ms: counter=90
t=100 ms: counter=90
t=200 ms: counter=80
t=280 ms: watchdog expired -> MCU reset (control task last checked in at 190 ms)
The control task last checked in at 190 ms, so the watchdog was never reloaded again and expired at 280 ms. An unconditional kick would have kept the device "alive" with a dead control task. After reset, read and log the cause (on STM32F4, IWDGRST in RCC_CSR).
21. Why use uint8_t and uint32_t instead of int and char?
Because the sizes of int and long, and even whether plain char is signed, change between compilers and chips. C only promises minimums: int must reach 32,767, so it may be 16 bits (C11 5.2.4.2.1). <stdint.h> types state the exact width that registers, protocol fields and buffers need.
char c = (char)200; /* plain char: signed or unsigned? */
printf("CHAR_MIN=%d, sizeof(long)=%zu, (char)200 == 200 ? %s\n",
CHAR_MIN, sizeof(long), (c == 200) ? "yes" : "no");
uint8_t u = 200u; /* fixed width: same on every target */
printf("uint8_t 200 == 200 ? %s\n", (u == 200u) ? "yes" : "no");
On the arm64 Mac host:
CHAR_MIN=-128, sizeof(long)=8, (char)200 == 200 ? no
uint8_t 200 == 200 ? yes
For the Cortex-M4 target, these compile-time checks passed:
_Static_assert(CHAR_MIN == 0, "plain char is unsigned on Cortex-M4");
_Static_assert(sizeof(long) == 4, "long is 32 bits on Cortex-M4");
_Static_assert(sizeof(int) == 4, "int is 32 bits on Cortex-M4");
On the host, plain char is signed and long is 8 bytes; on the Cortex-M4, char is unsigned and long is 4 bytes. C11 6.2.5p15 allows either kind of char, and converting 200 to a signed char is implementation-defined (6.3.1.3p3). So (char)200 == 200 was false on the host, and clang warned it always would be:
fixed_width.c:10:39: warning: result of comparison of constant 200 with expression of type 'char' is always false [-Wtautological-constant-out-of-range-compare]
CHAR_MIN, sizeof(long), (c == 200) ? "yes" : "no");
~ ^ ~~~
1 warning generated.
Keep plain char for text, uint8_t for bytes and uint32_t where width matters, as MISRA Directive 4.6 asks.
22. What is MISRA C, and why do automotive companies use it?
MISRA C is a set of guidelines for C in safety-related systems. It bans or restricts features that cause undefined or surprising behaviour, so code is easier to review and to check with static analysis tools. Automotive ECU teams use it because a software fault can hurt someone. The first edition came out in 1998; the current one is MISRA C:2025, published in March 2025 after MISRA C:2023 and MISRA C:2012.
Guidelines are either directives or rules, and each one is classed as Mandatory, Required or Advisory. These rules tie directly to the answers above:
| MISRA C:2012 guideline | Category | What it says | Question |
|---|---|---|---|
| Rule 9.1 | Mandatory | The value of an automatic variable shall not be read before it has been set | 8 |
| Rule 10.4 | Required | Both operands of an operator with usual arithmetic conversions shall have the same essential type category | 13 |
| Rule 15.6 | Required | Loop and if/switch bodies shall be compound statements (always use braces) | 15 |
| Rule 16.4 | Required | Every switch statement shall have a default label | 16 |
| Rule 17.2 | Required | Functions shall not call themselves, directly or indirectly (no recursion) | 6 |
| Rule 21.3 | Required | The memory allocation and deallocation functions of <stdlib.h> shall not be used | 7 |
| Directive 4.6 | Advisory | Typedefs that indicate size and signedness should be used in place of the basic numerical types | 21 |
Rule titles are as listed in MathWorks' Polyspace documentation; the full text is sold by MISRA. In an interview, explain why rules exist rather than reciting numbers: no recursion because stack use must be bounded, no malloc because memory must be predictable, fixed-width types because int changes size.
How should you prepare for an embedded C interview?
- Run the code. Compile each snippet with
-Wall -Wextra, change one thing, and predict the output before running it. - Read a disassembly.
objdump -don avolatileloop is the best answer to question 2. - Use one real board. Blink an LED through registers, receive UART bytes into a ring buffer from an ISR, and enable the watchdog. That covers half this list.
Skill-Lync's Embedded Programming Essentials course covers embedded C and pointers on STM32 microcontrollers. The PG Program in Embedded Systems for EV Applications adds RTOS, UART/SPI/I2C/CAN, MISRA C and AUTOSAR. Compare all options on the embedded systems courses page, revise interrupts and timers in the free microcontrollers book, and see embedded engineer fresher salaries and companies hiring embedded freshers. For other roles, start from the interview questions hub.
Frequently asked questions
What embedded C questions are asked for freshers?
Freshers are asked mostly about volatile, const pointers, static, bit manipulation (set, clear, toggle a bit), struct padding, endianness, and where variables are stored in memory. Expect one small program to write by hand, often a bit operation, a ring buffer or a string function, followed by "what happens if an interrupt fires here?"
Is volatile enough to share a variable between an ISR and main()?
Only for a single read or write that the CPU does in one access, such as a 32-bit flag on a 32-bit MCU. volatile stops the compiler from caching the value, but it does not make count++ or a 64-bit read atomic. Use a short critical section, a C11 atomic, or a re-read loop for those.
Which compiler should I practise embedded C with?
Any modern GCC or Clang on your laptop is enough for the C language questions; build with -std=c11 -Wall -Wextra and try -fsanitize=undefined. For target code, use the Arm GNU toolchain or your vendor's IDE (STM32CubeIDE, MCUXpresso, MPLAB X) and read the disassembly of small functions.
Do I need to memorise MISRA C rule numbers?
No. Interviewers want to know that MISRA C exists, why automotive projects use it, and the reasons behind its main rules: no dynamic memory, no recursion, fixed-width types, braces on every block and a default in every switch. Knowing one or two rule numbers, such as 21.3 on malloc, is a bonus.
Is Embedded C still worth learning in 2026?
Yes. Vendor HALs and register headers, like the ST and Arm files used in this guide, are written in C, and MISRA C got a new edition in March 2025. C++ and Rust are used in some teams, but reading and writing C is still the baseline skill for microcontroller firmware work.
Sources and further reading
- ISO/IEC JTC1/SC22/WG14, N1570, C11 committee draft (12 Apr 2011): clauses 4p6, 5.1.2.3, 6.2.2, 6.2.6.1, 6.3.1.1, 6.3.1.8, 6.5.7, 6.7.2.1, 6.7.3, 6.7.4, 6.7.9, 6.8.5, 7.14.1.1 and footnotes 95, 132, 134. Accessed 17 Nov 2026.
- ISO/IEC JTC1/SC22/WG14, N1169, draft TR 18037 "Extensions to support embedded processors" (2006), and the ISO/IEC TR 18037:2008 catalogue page.
- GCC manual, When is a Volatile Object Accessed? and Common Attributes (packed). Accessed 17 Nov 2026.
- The Linux kernel documentation, Why the "volatile" type class should not be used and Circular buffers. Accessed 17 Nov 2026.
- LLVM, UndefinedBehaviorSanitizer. Accessed 17 Nov 2026.
- STMicroelectronics, CMSIS device header stm32f407xx.h (memory map, GPIO and IWDG register definitions) and startup_stm32f407xx.s (reset sequence). Accessed 17 Nov 2026.
- STMicroelectronics, STM32F4 HAL IWDG driver and GPIO driver header. Accessed 17 Nov 2026.
- Arm, CMSIS-Core register access functions (__disable_irq, __get_PRIMASK, __set_PRIMASK) and core_cm4.h. Accessed 17 Nov 2026.
- Richard Barry, Mastering the FreeRTOS Real Time Kernel, chapter 7: Interrupt Management. Accessed 17 Nov 2026.
- MISRA, MISRA C history and editions; MathWorks Polyspace, MISRA C:2012 Rule 21.3, Rule 17.2, Rule 9.1 and related rule pages. Accessed 17 Nov 2026.
- Arduino, Sketch build process. Accessed 17 Nov 2026.

