Programming Fundamentals · Interview question

What's the right way to write an event loop with while (1)?

A strong answer

Use while (1) { … } (or for (;;) { … }) only when you genuinely want a forever loop with internal exit conditions. The body must have a path out: typically if (done) break; or return or exit(). The shape is fine and is the canonical pattern for read-process loops, server main loops, and microcontroller polling loops. The risk is forgetting to add the exit path or making it unreachable. A common bug is mishandling EOF: while (1) { c = getchar(); if (c == '\n') break; } will hang forever if stdin closes without a newline; the right check is if (c == EOF) break;.

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

while & do-while Loops

Repeating work while a condition holds, and the one case (do-while) where the body has to run at least once before the test.

More while & do-while Loops questions

Browse all 472 interview questions
What's the right way to write an event loop with while (1)? | EmbeddedPrep.io