C Programming · Interview question

Why can't a normal function swap two ints, but a function taking pointers can?

A strong answer

C is strictly pass-by-value: when you call swap(x, y), the function receives copies of x and y in its own local parameters. Swapping those copies has no effect on the caller's originals, they're separate storage. To actually modify the caller's variables, you pass their addresses: swap(&x, &y). Now the function has pointers to the originals, and dereferencing (*a, *b) reads and writes the caller's actual memory. The pointers are still passed by value (the addresses are copied), but the addresses point at the same storage, so writes through them are visible to the caller.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Pointers & Addresses

A pointer is just a variable that holds an address. Master & and *, NULL, and how passing a pointer lets a function reach back and modify the caller's data.

More Pointers & Addresses questions

Browse all 472 interview questions
Why can't a normal function swap two ints, but a function taking pointers can? | EmbeddedPrep.io