Why can't you declare a variable inside the expression portion of a do while loop?

前端 未结 6 1988
独厮守ぢ
独厮守ぢ 2021-02-06 23:23

The following syntax is valid:

while (int i = get_data())
{
}

But the following is not:

do
{
} while (int i = get_data());
         


        
6条回答
  •  清歌不尽
    2021-02-06 23:40

    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.

提交回复
热议问题