You cannot check for the break condition in the loop header, since for that you would need to exclude the maximum value.
Instead, do the check in the loop body and leave the check in the header empty:
for (auto i = std::numeric_limits<int>::lowest(); ; ++i) {
std::cout << i << '\n';
if (i == std::numeric_limits<int>::max())
break;
}
With a do-while loop, you don't need to check inside the loop body, but you need to move the counter variable to the outer scope, and if you want to avoid undefined behavior, you can only use unsigned integer types:
auto i = std::numeric_limits<unsigned>::lowest();
do {
std::cout << i << '\n';
} while (i++ < std::numeric_limits<unsigned>::max());
Note that the i++
will overflow, but that only happens after acquiring the current value (we're using postfix increment.) With signed integers however, this overflow would be undefined behavior, and even though we're not using the value after the overflow occurs, undefined behavior can have unpredictable results, even before it actually occurred.