for
Versus while
In C++ the for
and while
loops are essentially equivalent. For example, the for
loop
for (init-expression; test-expression; update-expression){ statement(s)}
could be rewritten this way:
init-expression;while (test-expression){ statement(s) update-expression;}
Similarly, the while
loop
while (test-expression) body
could be rewritten this way:
for ( ;test-expression;) body
This for
loop requires three expressions (or, more technically, one statement followed by two expressions), but they can be empty expressions (or statements). Only the two semicolons are mandatory. Incidentally, a missing test expression in a for
loop is construed as true, so this loop runs forever:
for ( ; ; ) body
Because for
loops and
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.