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

Tricky Outputs & Gotchas — C Interview Q&A

All C topics

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

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

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

Example.cc
void copy(char *d, const char *s) {
    while ((*d++ = *s++)) ; /* copies incl. terminator */
}

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