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.
A Boolean condition is either true or false. The program stays in the loop so long as the Boolean condition is true (1). Repeat whatever VI's are in the box until the Boolean function (based on i and N) is true/false. A compound statement is a bunch of statements enclosed by curly braces!
There are just two values of type bool: true and false. They are used as the values of expressions that have yes-or-no answers. C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0.
To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.
Also, a numeric value of zero (integer or fractional), the null value ( None ), the empty string, and empty containers (lists, sets, etc.) are considered Boolean false; all other values are considered Boolean true by default.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With