在这种情况下有什么好处

编程入门 行业动态 更新时间:2024-10-25 04:21:33
在这种情况下有什么好处 - “for”或“while”(What's better in that context - `for` or `while`)

我已经读过一个地方,当你迭代某种数组/序列/列表/你调用它时,你应该使用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.

更多推荐

本文发布于:2023-07-29 20:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1319374.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在这种情况下   有什么好处

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!