Back to questions
JuniorTheoryCommon
What happens when you build and run this program?
#include <iostream>
int main() {
unsigned i = 2;
while (i >= 0) {
std::cout << i << '\n';
--i;
}
}It prints 2, 1, 0, then the largest unsigned value, and never stops
- Expecting the loop to stop at -1: an
unsignedvalue is never negative, so--iat0gives the largestunsignedvalue andi >= 0stays true. - Expecting undefined behavior: only signed overflow is undefined;
unsignedarithmetic wraps around by definition, so the loop keeps printing.
- How would you rewrite this countdown so it prints
2,1,0and stops, keepingiunsigned? - Which warning flags make GCC and Clang report that
i >= 0is always true here?