Interview Q&A · C · 12 questions in this topic
Tricky Outputs & Gotchas — C Interview Q&A
The prediction questions interviewers love — initialization, precedence, sizeof traps and undefined-behavior pitfalls. Part of Tricky Outputs & Coding Tasks · 202 questions in the C bank.
What is the output of `int a[5];` vs `int a[5] = {0};` at function scope?
Answer
At function scope, int a[5] leaves elements indeterminate (reading them is UB), while int a[5] = {0} zero-initializes every element. At file scope both zero-initialize (static storage).
Partial initialization zero-fills the rest: int a[5] = {1, 2} gives {1, 2, 0, 0, 0} — a handy zeroing idiom.
Example
void f(void) { int a[3]; /* indeterminate! */ int b[3] = {0}; /* {0, 0, 0} */ int c[3] = {1, 2}; /* {1, 2, 0}: rest zero-filled */ }
Why does `sizeof` lie about arrays passed to functions?
Answer
It does not lie — the parameter was never an array. The array decayed to a pointer at the call, so sizeof measures the pointer (8 bytes on 64-bit), not the 40 bytes of int[10].
Compute sizes before decay (sizeof a / sizeof a[0] at the definition) and pass counts explicitly; -Wsizeof-pointer-div warns on the suspicious division pattern.
Example
void g(int *a) { /* sizeof a == 8 (pointer), not 40 */ } int a[10]; /* g(a); // decay already happened */
💡 The parameter never was an array is the precise mental model.
What does `while (*d++ = *s++);` actually do (and what must hold)?
Answer
It copies bytes including the terminator (assignment value drives the loop, stopping after copying '\0'), advancing both pointers per element — the canonical strcpy. Preconditions: destination fits the source including +1, regions do not overlap (else memmove), and both are valid.
It depends on three precedence facts: postfix ++ binds tightest, unary * next, assignment lowest (but above ;).
Example
void copy(char *d, const char *s) { while ((*d++ = *s++)) ; /* copies incl. terminator */ }
Signed overflow, shift-out-of-range, divide-by-zero — which are UB?
Answer
All three are undefined behavior for integers: signed overflow wraps on no platform you may rely on, shifts by >= width or of negative values are UB, and division/modulo by zero traps. Unsigned arithmetic wraps modulo 2^N by definition (not UB), though still a logic bug if unintended.
Compilers exploit signed-overflow UB for optimization, so -fwrapv-style assumptions break under -O2.
Example
int m = INT_MAX; /* m + 1; // UB: signed overflow */ /* 1 << 99; // UB: shift too far */ unsigned u = UINT_MAX; u + 1; /* defined: wraps to 0 */
💡 Signed is UB, unsigned wraps — that pairing answers the whole family.
What is the most vexing parse equivalent in C (`int f();`)?
Answer
int f(); declares a function taking unspecified arguments (no arity checking!) — not an object, and in C it disables argument checks rather than constructing anything. Combined with missing prototypes, f(1, 2) may compile against int f().
Modern C writes int f(void) for zero parameters and compiles with -Wstrict-prototypes to outlaw the empty-paren form.
Example
/* int f(); // unknown args, unchecked — avoid */ int g(void); /* zero args, checked — correct */
💡 -Wstrict-prototypes turns this historical trap into a compile error.
Why does `if (x = 5)` compile, and is it ever intentional?
Answer
Assignment is an expression yielding the assigned value, so if (x = 5) assigns then tests 5 (always true) — almost always a == typo. The intentional form tests a computed value: if ((n = read(fd, buf, sz)) > 0), with extra parens proving deliberateness.
-Wparentheses warns on bare assignment in conditions; Yoda conditions (5 == x) are the older defense, parens the modern one.
Example
/* if (x == 5) // comparison: what you meant */ /* if ((n = getchar()) != EOF) // assignment: deliberate, parenthesized */
What happens when you `free` a pointer twice or use it after free?
Answer
Double-free corrupts heap metadata — exploitable, often crashing far from the bug. Use-after-free reads recycled memory (attacker-controlled in exploits) and is undefined behavior. Both may appear to work in small tests and detonate under optimization or load.
Discipline: single owner, exactly-once free, NULL-after-free for shared handles, ASan in every test run.
Example
free(p); p = NULL; /* reuse becomes safe no-op/crash, not silent UB */
Why must `new[]`-style thinking not leak into C (`malloc` count math)?
Answer
C has no array cookie: malloc(n * sizeof *p) allocates exactly the computed bytes, and n * size can overflow into a too-small buffer (calloc checks this; manual multiplication does not). Freeing needs no count — but the program must track lengths itself for every access.
Every malloc site needs overflow-safe sizing plus a stored length traveling with the buffer.
Example
size_t n = untrusted(); /* int *a = malloc(n * sizeof *a); // may wrap! */ int *b = calloc(n, sizeof *b); /* overflow-checked */
What do the `static`, `const`, `volatile`, `restrict` qualifiers each promise?
Answer
static: restricted visibility or persistent duration (linkage/duration, not optimization). const: no mutation through this name (checking aid). volatile: access memory every time, never cache/reorder (hardware/signals). restrict: sole access path, no aliasing (vectorization license).
One keyword per concern — reciting all four with their distinct promises is the complete qualifier doctrine.
Key points
- 1static — visibility/duration control.
- 2const — immutability contract.
- 3volatile — no caching/reordering.
- 4restrict — no aliasing (C99).
Example
/* void copy(int *restrict d, const int *restrict s, size_t n); */💡 One concern per qualifier is the framing that shows mastery, not memorization.
What is integer promotion surprise in `uint8_t a = 200, b = 100; a + b`?
Answer
Both promote to int before adding (small types always compute as int), so a + b is int 300 — no wrap. But storing back into uint8_t wraps modulo 256 (44). Comparisons and shifts on small types likewise operate promoted.
The rule cuts both ways: arithmetic is safe, narrowing assignment wraps — -Wconversion flags the silent narrowing.
Example
#include <stdint.h> uint8_t a = 200, b = 100; int sum = a + b; /* 300: promoted, no wrap */ uint8_t narrow = a + b; /* 44: wrapped on store */
What is use-after-scope (block-scope lifetime) UB with an example?
Answer
Objects die at their closing brace; any pointer retained past it dangles — loop-body buffers returned outward, compound-literal addresses escaping, alloca results returned. The memory may look intact until reuse, then corrupt mysteriously.
Rule: no pointer outlives its brace. For escaping data, malloc (documented transfer) or caller-provided buffers.
Example
int *p = NULL; { int tmp = 5; p = &tmp; } /* tmp dies here: p dangles */ /* *p; // UB */
💡 No pointer outlives its brace is the lifetime mantra.
What do `static_cast`-style explicit conversions look like in C (casts)?
Answer
C casts (type)expr force conversions: numeric (double to int truncates), pointer (needs exact-round-trip discipline), const-stripping (writing to truly-const is UB), and void* (implicit in C, unlike C++). Every cast silences the compiler — so each needs a comment justifying why the warning was wrong.
Fewest casts wins: clean C compiles with -Wconversion nearly silent.
Key points
- 1Numeric — truncation and sign rules apply.
- 2Pointer — exact round-trip or UB.
- 3Const-strip — UB on truly-const targets.
Example
double d = 3.99; int i = (int)d; /* 3: truncation, explicit and intended */
💡 Each cast needs a justification comment — that review rule answers the philosophy half.
Recommended resourcesAffiliate links · may earn us a commission