Interview Q&A · C · 14 questions in this topic
Advanced C Idioms — C Interview Q&A
Senior-level C — qualifiers, restrict, function pointers, opaque types, and building data structures from scratch. Part of Advanced C Idioms · 202 questions in the C bank.
What does `const` mean in all its positions (data, pointer, parameter)?
Answer
const promises no mutation through that name: const int n (object immutable), const char *p (pointee immutable), char *const p (pointer immutable), const member intent via const-correct APIs. It is a compile-time contract — casts can strip it, but writing to truly-const storage is undefined behavior.
const-correct APIs (const inputs, mutable outputs) move mutation bugs from production to compile time.
Example
size_t strlen(const char *s); /* promises not to mutate */ /* const int LIMIT = 100; */ /* int *const fixed = buf; // reseat banned */
💡 Const on inputs, mutable only on outputs is the API design rule.
What does `restrict` mean and what optimization does it unlock?
Answer
restrict (C99) promises that a pointer is the sole access path to its object within its scope — no aliasing through other pointers. The compiler then reorders, vectorizes and caches loads freely (memcpy-style speedups). Violating the promise (overlapping restrict pointers) is undefined behavior.
Use it on hot copy/math kernels with provably-disjoint buffers; never as a decoration on possibly-overlapping arguments.
Example
/* void copy(int *restrict dst, const int *restrict src, size_t n); */ /* // caller guarantees disjoint ranges: compiler may vectorize */
How do function pointers work, and how do you declare them readably?
Answer
A function pointer holds a callable address with an exact signature; call through it like the function. Read declaration inside-out (spiral rule) or — better — typedef the type once: typedef int (*cmp_t)(const void*, const void*).
Uses: qsort/bsearch comparators, callbacks, dispatch tables, state machines, and test seams (inject fake implementations).
Example
typedef int (*cmp_t)(const void *, const void *); int cmp_int(const void *a, const void *b) { int x = *(const int *)a, y = *(const int *)b; return (x > y) - (x < y); } /* qsort(arr, n, sizeof *arr, cmp_int); */
💡 Typedef once, use everywhere — decoding skill is for interviews, typedefs are for codebases.
How do callbacks with `void *context` work (and why is context needed)?
Answer
C callbacks pair a function pointer with an opaque void* context the caller provides and the callee threads back — the C substitute for closures/captures. The callback casts context to its real type. NULL context must be documented as allowed or forbidden.
Lifetime rule: the context must outlive every possible invocation (beware async callbacks after free).
Example
typedef void (*visit_t)(int value, void *ctx); void walk(int *a, size_t n, visit_t fn, void *ctx) { for (size_t i = 0; i < n; i++) fn(a[i], ctx); }
How do `qsort` and `bsearch` work? What must comparators guarantee?
Answer
qsort sorts via your comparator (negative/zero/positive, consistent strict ordering); bsearch binary-searches a sorted array with the same-style comparator and key. Both are generic through void* plus element size. The comparator must be a consistent strict weak ordering — inconsistent comparators corrupt sorts silently.
Cast inside to the real const-qualified type; never mutate through the comparator.
Example
#include <stdlib.h> /* qsort(a, n, sizeof *a, cmp_int); // sorts in place */ /* int key = 7; */ /* int *hit = bsearch(&key, a, n, sizeof *a, cmp_int); */
How do you implement a generic dynamic array (vector) in C?
Answer
Struct with (data, len, cap, elem_size); growth by geometric doubling with the realloc-temporary pattern; memcpy element moves; full lifecycle (init/push/get/free) with ownership documented. Type safety comes from wrapper macros or per-type instantiations over a void* core.
This is the data-structure-from-scratch question — narrate growth, amortization and ownership as you write it.
Key points
- 1Header — length, capacity, element size.
- 2Growth — double on full (amortized O(1) push).
- 3Ownership — free function mirrors init; elements shallow unless cloned.
Example
typedef struct { void *data; size_t len, cap, elem; } vec_t; /* push: if (len == cap) grow(); memcpy(slot, val, elem); len++; */
💡 Say amortized O(1) and the realloc-temporary pattern while sketching — both are graded.
How do you implement a linked list in C (and intrusive vs allocated nodes)?
Answer
Allocated nodes: malloc per node with next/prev pointers — simple, cache-hostile, malloc-heavy. Intrusive: embed the link struct in the object, recover via container_of — zero extra allocations, kernel-style. Both need crystal-clear ownership (who frees, when) and sentinel/dummy-head discipline to kill special cases.
Draw one insertion (four pointer updates for doubly-linked) — interviewers watch the ordering.
Example
typedef struct node { int v; struct node *next; } node_t; /* push front: n->next = *head; *head = n; // order matters */
How do you implement a hash table in C (chaining vs open addressing)?
Answer
Chaining: bucket array of linked lists — simple deletion, pointer chasing, malloc per entry (or entry pools). Open addressing (linear probing/robin-hood): single array, cache-friendly, tricky deletion (tombstones) and load-factor discipline (<0.7 typical).
Hash with FNV-1a or splitmix over bytes (never identity on attacker input — hash flooding), grow by rehashing, and test with pathological key sets.
Key points
- 1Chaining — simple, allocation-heavy.
- 2Open addressing — fast, deletion needs tombstones.
- 3Both — hash quality plus resize discipline decide performance.
What is `_Generic` (C11) and what is it good for?
Answer
_Generic selects an expression by its type at compile time — the building block for type-safe macro APIs (a poor-man's overloading): cbrt macro dispatching float/double/long double variants, print helpers, min/max without double evaluation.
It selects on the controlling type only (no conversions ranking), so cover exactly the types you support and static-assert the rest away.
Example
#include <math.h> #define cbrt_g(x) _Generic((x), float: cbrtf, double: cbrt, \ long double: cbrtl)(x)
💡 Type-safe macros without double evaluation is the _Generic elevator pitch.
What are `static_assert` / `_Static_assert` and where do they pay off?
Answer
Compile-time assertions that fail the build with a message when an assumption breaks: struct sizes for wire formats, alignment, table lengths matching enums, API constants. They convert runtime mysteries into build errors at the exact invariant.
Place them beside the assumption (not in a distant test): layout checks next to the struct, protocol sizes next to the protocol.
Example
#include <assert.h> /* static_assert(sizeof(header_t) == 16, "wire format changed"); */
💡 Sizes, alignments and enum-table parity are the three classic placements.
How do you handle errors without exceptions (codes, goto cleanup, Result types)?
Answer
Layer the strategy: leaf functions return codes/NULL with errno detail; mid layers propagate with context added; resource-heavy functions funnel through goto cleanup; rich APIs return result structs (value + error) or out-param plus status. Sentinel returns (NULL/-1) need documented errno/flag partners.
Consistency beats cleverness: one project-wide convention, enforced in review.
Key points
- 1Leaf — codes with errno detail.
- 2Layers — propagate, adding context.
- 3Resources — single cleanup label.
Example
typedef struct { int value; int err; } result_t; /* result_t parse(const char *s); // value valid iff err == 0 */
How do `setjmp`/`longjmp` work, and why are they dangerous?
Answer
setjmp saves registers/stack context into a jmp_buf (returns 0); longjmp restores it, teleporting control back (setjmp appears to return nonzero). Dangers: no unwinding — malloc locks, file state and intermediate invariants are abandoned; volatile is required for locals modified between (else indeterminate); crossing function returns is UB.
Legitimate niche: parsers and interpreters unwinding deep recursion on fatal errors. Everywhere else, return codes win.
Example
#include <setjmp.h> /* jmp_buf env; */ /* if (setjmp(env) == 0) { deep(); } else { /* unwound here */ } */ /* longjmp(env, 1); // teleport back (no cleanup runs!) */
How do you write portable C (compilers, platforms, endianness)?
Answer
Fixed-width stdint types, no assumed sizes/endianness, feature macros over platform checks where possible, strict warnings on multiple compilers (gcc/clang/MSVC), and CI matrices across OS/architecture. Serialize with explicit byte order (hton/ntoh or manual shifts), never struct dumps.
Portability is tested, not claimed: cross-compile plus QEMU/thread-sanitizer runs prove it.
Key points
- 1Types — stdint, never long-assumptions.
- 2Bytes — explicit order on the wire.
- 3Proof — multi-compiler, multi-arch CI.
Example
/* uint32_t v = ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) | ...; */💡 Never struct-dump to disk/wire is the portability commandment.
What C habits mark code as genuinely professional?
Answer
Ownership in comments and names, const-correct APIs, checked allocations, bounded string handling, -Wall -Wextra -Werror clean builds, sanitizer-tested suites, small modules with opaque types, and no cleverness without a comment explaining why.
Professional C is boring C: explicit, checked, and reviewable — the language punishes flair.
Key points
- 1Safety — checked, bounded, sanitized.
- 2Modularity — opaque types, small APIs.
- 3Honesty — boring code with reasons documented.
💡 Close with boring-on-purpose — it reads senior in C culture.
Recommended resourcesAffiliate links · may earn us a commission