A question mostly for fun/curiosity: how to write a for
loop in C++ that would iterate over two values of a bool
(i.e. true
and false
), using only operations with bool
(i.e. without conversions to other types)?
The background is that I wanted to check how many solutions exists for an equation like (A && B) || (!B && !C && !D) == true
, and started to write something like for (bool A=false; ??? ; ++A) for (bool B=false; ...)
etc but immediately got stuck by ???
- i.e. what would be the condition to continue the loop? Of course I rewrote it to use int, and I also know that a do ... while
loop will work, but I got curious if it's ever possible to write such a for
loop? And since SO does not seem to have an answer, I decided to ask :)
Update: note that an "obvious" variant for(bool A=false; !A; A=true)
suggested in at least two now-removed answers will only run one iteration, because for the second one the condition !A
becomes false
and the loop ends.
After some pondering, I believe it's impossible to do it in C++03 without a second variable or a pointer based construct like suggested by Dietmar Kühl. The condition should be tested three times in a desired execution, so two values of a bool are simply not enough. And the do-while loop works because the first iteration is executed unconditionally, the condition is only checked twice and so a bool value can be used to select between continuing and exiting.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…