Programming Fundamentals · Interview question

What does scanf return, and why should you check it?

A strong answer

scanf returns the count of successfully parsed items, or EOF on input failure / end of stream. If your format string says "%d %d" and the user types "5 hello", you get 1 back, only the first %d matched. If you ignore the return value, the second variable is uninitialized garbage and your program proceeds as if everything worked. The defensive habit is if (scanf("%d", &n) != 1) { error… }, it catches malformed input before bad data spreads through the rest of the program. This is the same lesson as checking every system-call return value: ignoring failure modes is how silent corruption begins.

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

Input & Output

How a program talks to the outside world. printf and scanf in C: format specifiers, common traps, and why the return value matters.

More Input & Output questions

Browse all 472 interview questions
What does scanf return, and why should you check it? | EmbeddedPrep.io