Programming Fundamentals · Interview question

Why does while (i >= 0) with an unsigned i never exit?

A strong answer

Unsigned integers are by definition non-negative, the type can't represent a negative value. When i is 0 and we do i--, the result doesn't go to -1; it wraps around to UINT_MAX (the largest representable unsigned value), which is a huge positive number. The condition i >= 0 is now still true, and stays true forever, wrapping resets the count instead of letting the loop terminate. The fix is either to use a signed type (int) so the count can actually go negative, or to restructure the loop: while (i > 0) { use(i); i--; }, which decrements only after using a positive value.

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
Why does while (i >= 0) with an unsigned i never exit? | EmbeddedPrep.io