(提前抱歉,这个问题可能很简单。我把编写代码作为一种爱好,现在只是想把我的想法集中在一些事情上。)
最近遇到这样的循环语句(n
是之前设置的正整数):
int cnt;
for(cnt=0; n; cnt++){
n &= n - 1;
}
如果我没理解错的话,一个循环的中间入口应该是一个条件,但是n;
好像根本就不是一个条件。除非它被理解为 bool (true
if n!=0
and false
if n==0
).如果这是正确的思考方式,那么下面的代码是否完全等同于上面的代码?
int cnt=0;
while(n>0){
n &= n - 1;
cnt++;
}
如果是,为什么要选择前一种写法而不是 while 循环?在我看来,while 循环将是这里最清晰和直观的选择,所以我想知道我错过的 for 循环是否有任何优势?感谢您的任何建议!
最佳答案
If I understand correctly, the middle entry in a loop should be a condition, but n; does not seem to be a condition at all.
是的。
Unless if it is understood as a bool (true if n!=0 and false if n==0).
是的。
If this is the correct way to think about it, would the following code be perfectly equivalent to the above?
几乎;它是 n != 0
,而不是 n > 0
。
If yes, why would one choose the former style of writing this instead of the while loop?
人们总是出于各种原因做傻事!
It seems to me that a while loop would be the most clear and intuitive choice here
我同意。
I wonder if there is any advantage in the for loop that I missed?
没有。
嗯,不是这个。如果循环体不同,比如说有更复杂的逻辑和一两个 continue
语句,程序的行为可能会不同(如果你忘记在你的上递增 cnt
新的代码路径)。但这里不是这种情况。
关于c++ - for 循环中没有条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41313299/