Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

c++ - How to write a `for` loop over bool values (false and true)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...