简体   繁体   中英

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM