問題描述
一個主要是為了好玩/好奇的問題:如何在 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 }) {/* ... *