How to write a `for` loop over bool values (false and true)
Solution 1:
In C++11: for (bool b : { false, true }) { /* ... */ }
Here's a C++03 version:
for (bool a = true, b = false; b != a; a = a && b, b = !b) { /*...*/ }
(Use either a
or b
.)
Solution 2:
When restricted to C++2003 you could use an approach roughly equivalent to the C++2011 approach;
{
bool const bools[] = { false, true };
for (bool const* it(bools); it != std::end(bools); ++it) {
bool a(*it);
use(a);
}
}
Possibly packed up in a macro. You can also use
for (bool a: { false, true }) {
use(a);
}
Solution 3:
for (int a = 0; a <= 1; a++)
doStuff(a ? true : false);
And forget about "no conversions to other types" restriction :) In the end of the day clarity is more important than artificial restrictions. Five years down the line you'll be reading your own code and wondering "what the heck was I thinking, is this some sort of an obfuscation contest?"
Solution 4:
a = true;
do {
use(a);
a = !a;
} while (!a);
OK, so it's not a for loop, but I would argue it is more readable than any of the for loop suggestions (other than the C++11 approach, of course.)
Solution 5:
One more for C++03:
for(bool a = false, b = true; b; a = !a, b = a)
Use b.