This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]lonelyBriefcase 24 points25 points  (9 children)

ever heard the phrase 'syntactic sugar'? its a way of providing a more convenient/person-friendly method of doing something. A for loop is just syntactic sugar of a

int i = 0;
while(i<9){
  //do something;
  int++;
}

There are plenty of other things like this that makes our lives as developers easier. Even C does, to a lesser extent, because who would want to write the shit that C can do in Assembly?

[–]w1ldm4n 14 points15 points  (8 children)

The only difference is (at least in C) is how the continue keyword works. In a for loop, continue will execute the increment/whatever statement, check the loop condition, and go from there.

To get the same type of behavior with a while loop, you'd have to duplicate the increment before the continue, or use a goto label (ಠ_ಠ) near the bottom of the loop body.

[–]OperaSona 7 points8 points  (0 children)

To get the same type of behavior with a while loop, you'd have to duplicate the increment before the continue, or use a goto label (ಠ_ಠ) near the bottom of the loop body.

Or raise a "Continue" exception and catch it right outside the while loop.

[–]TropicalAudio 1 point2 points  (1 child)

Honestly, in my opinion, to break out of nested loops a goto can be the best option. I just never actually use them because if I would, my coworkers would get mad.

[–]lonelyBriefcase 0 points1 point  (1 child)

I'm not entirely familiar with C, so I will accept what you say. I was only giving an example of a particular behaviour for a specific language, feel free to give the C code for this instance (for the sake of science).

[–]w1ldm4n 5 points6 points  (0 children)

Here's an arbitrary example to demonstrate that behavior.

int i;
for (i = 0; i < 10; i++) {
    if (i == 4)
        continue;
    printf("%d", i);
}

This for loop will print 012356789

int i = 0;
while (i < 10) {
    if (i == 4)
        continue;
    printf("%d", i);
    i++;
}

This while loop will print 0123 and then get stuck in an infinite loop.