The following syntax is valid:
while (int i = get_data()) { }
But the following is not:
do { } while (int i = get_data());
We can see why via the draft standard N4140
section 6.4:
1 [...]
condition: expression attribute-specifier-seqoptdecl-specifier-seq declarator = initializer-clause attribute-specifier-seqoptdecl-specifier-seq declarator braced-init-list2 The rules for conditions apply both to selection-statements and to the
for
andwhile
statements (6.5). [...]
and section 6.5
1 Iteration statements specify looping.
iteration-statement:while
( condition ) statementdo
statementwhile
( expression ) ;
Instead, you're forced to do something ugly like:
int i = get_data(); do { } while ((i = get_data())); // double parentheses sic
What is the rationale for this?
Yes. you can declare a variable inside any loop(includes do while loop.
If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.
The do-while loop iterates a section of the C++ program several times. In the do-while loop, test expression is added at the bottom of the loop. The loop body comes before the test expression. That's why the loop body must execute for once, even when test expression evaluates to false in the first test.
It seems like scoping would be the issue, what would be the scope of i
declared in the while
portion of a do while
statement? It would seem rather unnatural to have a variable available within the loop when the declaration is actually below the loop itself. You don't have this issue with the other loops since the declarations comes before the body of the loop.
If we look at the draft C++ standard section [stmt.while]p2 we see that for the while statement that:
while (T t = x) statement
is equivalent to:
label: { // start of condition scope T t = x; if (t) { statement goto label; } } // end of condition scope
and:
The variable created in a condition is destroyed and created with each iteration of the loop.
How would we formulate this for the do while
case?
and as cdhowie points out if we look at section [stmt.do]p2 it says (emphasis mine):
In the do statement the substatement is executed repeatedly until the value of the expression becomes false. The test takes place after each execution of the statement.
which means the body of the loop is evaluated before we would even reach the declaration.
While we could create an exception for this case it would violate our intuitive sense that in general the point of declaration for a name is after we see the complete declaration(with some exceptions for example class member variables) with unclear benefits. Point of declaration is covered in section 3.3.2
.
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