Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does c++(and most other languages) have both 'for' and 'while' loops?/What can you do with one type that you can't with the other?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading