我已经读过一个地方,当你迭代某种数组/序列/列表/你调用它时,你应该使用for循环,当你的循环需要在某个条件下停止时,我应该使用while循环。
那么,如果我有这样的东西怎么办?
int len = 0; for(; s[len] != '\n'; ++len) { // some processing if (someCondition) { return len; } } // if done iterating, return len return len;在这种情况下可以使用for循环还是优先使用while循环?
I've read somewhere that one should use a for loop when you are iterating over some sort of array/sequence/list/whatever you call it and a while loop when your loop needs to stop at a certain condition.
So, what if I have something like this
int len = 0; for(; s[len] != '\n'; ++len) { // some processing if (someCondition) { return len; } } // if done iterating, return len return len;Is this okay to use the for loop in this context or would a while loop be preferable?
最满意答案
我可能会这样写:
int len; for (len = 0; s[len] != '\n'; ++len) { ... } return len;因为那时我在for语句中说了我感兴趣的范围(索引0直到第一个换行符)。
我通常在代码看起来的基础上选择for和while ,而不是我在发型语义论证中的位置,“某种范围”与“从现在到某些条件为假的时间段”之间的区别是什么”。 我认为玩一下这个问题并不是一个问题。 声明的第三部分是“特别可见的”,因为while循环结束时的增量不是,并且我认为这足以证明使用它与一个小的扭曲如空的第一部分。
I'd probably write it this way:
int len; for (len = 0; s[len] != '\n'; ++len) { ... } return len;Just because then I say in the for statement what the range is I'm interested in (index 0 up to the first newline character).
I generally choose between for and while on the basis of what the code looks like, rather than on where I stand in the hairsplitting semantics argument what the difference is between "some kind of range" vs "the period from now until some condition is false". I don't think it's a problem to play around a bit with for. The third part of the statement is "specially visible" in the way that an increment at the end of a while loop isn't, and I think that's enough to justify using it with a minor contortion like your empty first part.
更多推荐
发布评论