4 ms·
I think a lot of the pitfalls with unsigned types relates to the for loop construct being biased towards counting up. Consider the following code, the down for
by detrino 13y ago
I think a lot of the pitfalls with unsigned types relates to the for loop construct being biased towards counting up. Consider the following code, the down for loop is really ugly and unintuitive, but the down while loop is symmetrical to the up loop. Maybe C/C++ need a counterpart to the for loop where the loop body executes last?
#include <iostream>
int main()
{
unsigned I;
// 0 to 4, for loop
for (I = 0; I != 5; ++I) std::cout << I << "\n";
std::cout << "\n";
// 4 to 0, for loop
for (I = 5; I-- != 0;) std::cout << I << "\n";
std::cout << "\n";
// 0 to 4, while loop
I = 0;
while (I != 5)
{
std::cout << I << "\n";
++I;
}
std::cout << "\n";
// 4 to 0, while loop
I = 5;
while (I != 0)
{
--I;
std::cout << I << "\n";
}
std::cout << "\n";
}