5

I'm currently studying computer science in Germany but did work on several C/C++ opensource projects before. Today we kind of started with C at school and my teacher said it would be a no go to modify a for loop variable inside the loop, which I absolutely agree with. However, I often use a for loop without the last incrementing part and then modify it only inside the loop, which he also did not like.

So basically it comes down to

for(int i=0; i<100;) {
    [conditionally modify i]
}

vs

int i=0;
while(i<100) {
    [conditionally modify i]
}

I know that they are essentially the same after compile, but I don't like using a while loop because:

  1. It's common practice to limit variables to smallest possible scope
  2. It can introduce bugs if you reuse i (which you have to because of larger scope)
  3. You can not use a different type for i in a later loop without using a different name

Are there any style guides/common practices which one to choose ?

If you answer with "I like while/for more" at least provide a reason why you do so.

I did already search for similar questions, however, I could not find any real answer to this case.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Thalhammer
  • 285
  • 3
  • 7
  • 1
    There is no "hard rule" against your use of a for-loop. If you need it, use it. Check if there is some algorithm of standard library method that solves the underlying problem first, though. (Speaking mostly from a C++ iterator loop POV here, the tag was since removed.) – Baum mit Augen Oct 17 '17 at 10:01
  • 1
    smh i don;t like `[conditionally modify i]` part. What if, the condition is never met? – Sourav Ghosh Oct 17 '17 at 10:01
  • *"my teacher said it would be a no go to modify a for loop variable inside the loop, which I absolutely agree with"*: did you ask your teacher why he think so? Why you agree with him? – haccks Oct 17 '17 at 10:01
  • Possible duplicate of [Iterate with for loop or while loop?](https://stackoverflow.com/questions/99164/iterate-with-for-loop-or-while-loop) – Techy Oct 17 '17 at 10:01
  • 1
    @Techy why tag a java dupe for a C question? – Sourav Ghosh Oct 17 '17 at 10:02
  • While this appears subjective at first sight, the 3 reasons given are a clear sign that this is at the very least a _good subjective_ question. – MSalters Oct 17 '17 at 10:04
  • @SouravGhosh - There's more than one way to interpret *"conditionally modify i"*. One may also read this as *"i is modified in several ways, depending on a condition"*. – StoryTeller - Unslander Monica Oct 17 '17 at 10:04
  • @SouravGhosh I assume that one does not create a infinite loop. See StoryTeller – Thalhammer Oct 17 '17 at 10:08
  • @haccks Because if I see a i++ in the loop head I assume it to be a simple iterating loop and would not expect a change of i in the body. If however in the head there is nothing I expect i to change somewhere inside the body. – Thalhammer Oct 17 '17 at 10:08
  • note that you can limit scope by enclosing the while() inside a {} block as well. Not that I'm suggesting it, it's just that the two loop forms are really functionally equivalent and hence choosing one over the other it's entirely a matter of readability, mantainability, error proneness, ... just too broad yet too trivial to be answered here IMO – Massimiliano Janes Oct 17 '17 at 10:20
  • 1
    At least you didn't ask us to choose between `while(1)` and `for(;;)`. Then you'd have a true flame war on your hands. – StoryTeller - Unslander Monica Oct 17 '17 at 10:28
  • If you *can* concentrate the loop-machinery into one line, IMHO you should certainly do that. If you *cannot*, you should try to find the best candidate for the termination condition, and use that in either a `while(cond){}` or `for(;cond;){}` If you *cannot* find any usable condition (yet), just use `1` as a condition (using {break,continue,return,goto} to drive the loop) and maybe restructure later, once you discouvered the most robust&sensible loop condition(s). – joop Oct 17 '17 at 11:26
  • @StoryTeller: I have a compelling argument against `while (1)`: it looks confusingly close to `while (l)`. Of course the same argument should ban `l` as a variable name. – chqrlie Oct 18 '17 at 09:51
  • @chqrlie - That argument still won't stop a flame war, I'm afraid. In fact, I think it may just start another one. – StoryTeller - Unslander Monica Oct 18 '17 at 09:53
  • @StoryTeller: Is there a stackexchange site dedicated to flame wars and trolls? So many questions to ask (and self answer) there... – chqrlie Oct 18 '17 at 09:58
  • @chqrlie - I dunno. But now that you mention it, I think there should be one :) – StoryTeller - Unslander Monica Oct 18 '17 at 09:59

4 Answers4

3

Style guides differ between different people / teams.

The C standard describes the syntax of for like this:

for ( clause-1 ; expression-2 ; expression-3 ) statement

and it's common practice to use for as soon as you have a valid use for "clause-1", and the reason to do so is indeed because of the limited scope:

[...] If clause-1 is a declaration, the scope of any identifiers it declares is the remainder of the declaration and the entire loop, including the other two expressions; [...]

So, your argumentation is fine, and you could try to convince your teacher. But don't try too hard. After all, questions of style rarely have one definitive answer, and if your teacher insists on his rules, just follow them when coding for that class.

  • I'll add that if you write code for a living, you're likely to work under style guides that specify different ways to code loops like this. – Andrew Henle Oct 17 '17 at 10:53
1

There are some common practices which programmers follow while taking the decision on which loop to use - for or while!

The for loop seems most appropriate when the number of iterations is known in advance. For example -

/*N - size of array*/
for (i = 0; i < N; i++) {
  ...
}

But, there could be many complex problems where the number of iterations depend upon a certain condition and can't be predicted beforehand, while loop is preferable in those situations. For example -

while( fgets( buf, MAXBUF, stdin ) != NULL)

However, both for and while loops are entry controlled loops and are interchangeable. Its completely up to the programmer to take the decision on which one to use.

H.S.
  • 11,654
  • 2
  • 15
  • 32
1

If you are modifying the loop counter inside the body, I would recommend not using a for loop because it is more likely to cause reader's confusion than the while loop.

You can work around the lack of scope limitation with an additional block:

{
    int i = 0;
    while (i < 100) {
        [conditionally modify i]
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
0
    for(int i=0; i<100;) {
[conditionally modify i]
}

Because this looks confusing, not standard way to write for loop. Also, conditionally modify i is dangerous, you don't want to do that. Someone reading your code would have problems understanding how you increment, why, when..etc. You want to keep your code clean and easy to understand.

I would personally never write for loop with conditionally modifying iterator. If you need it, you can use additional counter, or something like that. But you shouldn't control flow with conditioning iterator, some people even avoid break and continue.

marko
  • 77
  • 7
  • 2
    I won't downvote, but I disagree. While conditional modification is a bit ugly, it's not dangerous. And it is in some cases necessary or at least more readable than the alternative. – user694733 Oct 17 '17 at 10:34
  • Maybe sometimes, but he asked this question in general, right? Imagine reading someone code and for every loop you need to deduce how it increments. And i just don't like controlling flow of loop with playing with iterator, i think there are better ways to do that. – marko Oct 17 '17 at 10:42
  • I agree with your explanation, but it is an argument for the `while` loop, not the `for` loop. – chqrlie Oct 18 '17 at 10:01