Home > OS >  Why does c (and most other languages) have both 'for' and 'while' loops?/What c
Why does c (and most other languages) have both 'for' and 'while' loops?/What c

Time:10-11

Why do most programming languages have two or more types of loops with almost no difference? In c , is one of the two better for specific tasks? What about switches and if's; is there any difference there?

If not, then an answer about why they were implemented would be appreciated.

CodePudding user response:

There is nothing that you can do with one type that you can't do with the other, because mechanical transformations exist between them:

while (X) { body; }

can be written as

for (;X;) { body; }

and

for (A;B;C) { body; }

can be written as

{ A; while (B) { body; C; } }

The only difference is readability. The for loop puts the update-expression C at the top of the loop, making it easier to recognize certain patterns like looping through a numeric range:

for( i = 0; i < limit;   i )

or following a linked list

for( ; ptr != nullptr; ptr = ptr->next )
  • Related