一个主要是为了好玩/好奇的问题:如何在 C++ 中编写一个 for 循环来迭代 bool 的两个值(即 true 和 false),仅使用 bool 的操作(即不转换为其他类型)?
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)?
背景是我想检查像 (A && B) || 这样的方程有多少解(!B && !C && !D) == true,然后开始写类似 for (bool A=false; ??? ; ++A) for (bool B=false; ...) 等,但立即被 ??? 卡住 - 即继续循环的条件是什么?当然,我将它改写为使用 int,而且我也知道 do ... while 循环会起作用,但是我很好奇是否有可能编写这样的 for 循环?由于 SO 似乎没有答案,我决定问:)
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 :)
更新:请注意,在至少两个现已删除的答案中建议的明显"变体 for(bool A=false; !A; A=true) 只会运行一次迭代,因为对于第二个条件 !A 变为 false 并且循环结束.
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.
经过深思熟虑后,我相信在没有第二个变量或像 Dietmar Kühl 建议的基于指针的构造的情况下,在 C++03 中是不可能做到的.条件应在所需的执行中测试 3 次,因此布尔值的两个值根本不够.do-while 循环之所以有效,是因为第一次迭代是无条件执行的,条件只检查两次,因此可以使用 bool 值在继续和退出之间进行选择.
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.
C++11: for (bool b : { false, true }) {/* ... *
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)