
我最近遇到了一个循环语句,如(n是先前设置的正整数):
int cnt;for(cnt=0; n; cnt++){ n &= n - 1;} 如果我理解正确,循环中的中间条目应该是一个条件,但是n;似乎根本不是一个条件.除非它被理解为bool(如果n!= 0则为true,如果n == 0则为false).如果这是考虑它的正确方法,那么以下代码是否完全等同于上述代码?
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循环中没有条件?全部内容,希望文章能够帮你解决c – for循环中没有条件?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)