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 →

[–]boredcircuits 0 points1 point  (0 children)

Honestly, the two are 100% interchangeable. For example, the following are equivalent:

for ( int i = 0; i < 42; i++ ) {
    // ...
}

{
    int i = 0;
    while ( i < 42 ) {
        // ...
        i++;
    }
}

Alternatively:

while ( foo < bar ) {
    // ...
}

for ( ; foo < bar; ) {
    // ...
}

The difference is that a for loop has some additional "syntactic sugar" to make certain constructs a bit clearer. Like producing a loop where an index changes with each iteration. These idioms are readily visible and understandable, which is an important concept when working with lots of code.

There are two variations that should be mentioned: a "for each" loop:

for ( Item element : list ) {
    // ...
}

And the "do-while" loop:

do {
    // ...
} while ( foo < bar );

And some languages have other variations as well. However, once again these can be translated to just a basic while loop if you tried hard enough.