Interview Q&A · C · 14 questions in this topic

Advanced C Idioms — C Interview Q&A

All C topics

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

Example.cc
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

Example.cc
/* 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

Example.cc
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.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits