In C++ you are allowed to have an empty condition inside the for-loop, for example as in for (;;)
or for (int x = 0;; ++x)
. But you can't do while ()
.
When condition is omitted inside the for loop, condition is assumed to be true
(so the loop loops forever). Why isn't this the case with while
loops, that is, what's the argument behind not letting while ()
be an alias of while (true)
?
A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".
The while loop is used when we don't know the number of times it will repeat. If that number is infinite, or the Boolean condition of the loop never gets set to False, then it will run forever.
A for loop works as long as the condition is true. The flow of control, at first comes to the declaration, then checks the condition. If the condition is true, then it executes the statements in the scope of the loop. At last, the control comes to the iterative statements and again checks the condition.
while loop is executed once before the test expression is checked. The syntax of repeat..while loop is: repeat { // body of loop } while (condition) Here, The body of the loop is executed at first. Then condition is evaluated.
Presumably, it's a side-effect of the fact that each given clause within the for-statement is optional. There's reasons why some for-loops wouldn't need an assignment; there's reasons why some others wouldn't need a condition; there's reasons why still others wouldn't need an increment. Requiring there to be some minimum number of them would be needlessly-added complexity.
The following is from the book Deep C Secrets:
Early C had no separate operators for & and && or | and ||. (Got that?) Instead it used the notion (inherited from B and BCPL) of "truth-value context": where a Boolean value was expected, after "if" and "while" and so forth, the & and | operators were interpreted as && and || are now; in ordinary expressions, the bitwise interpretations were used. It worked out pretty well, but was hard to explain. (There was the notion of "top-level operators" in a truth-value context.)
So there you have it, while()
would set the context for a truth value and can't be empty or implied for the same reason if() can't be empty, the mechanics of the early language expected them not to be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With