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

前端 未结 6 1986
独厮守ぢ
独厮守ぢ 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:46

    There are several reasons for why it would be difficult to allow.

    The language sticks to the general rule that everything should be declared above the point of usage. In this case the variable declared in do-while would be declared below its expected natural scope (the cycle body). Making this variable accessible inside the cycle would've required a special treatment for do-while cycles. Even though we know examples of such special treatment (e.g. in-class member function bodies can see all class members, including the ones declared below), there's probably not much practical sense in doing it for do-while cycles.

    In case of do-while these special treatment rules would also require finding a meaningful way of handling initialization of variables declared in this fashion. Note that in C++ language the lifetime of such variable is limited to one iteration of the loop, i.e. the variable is created and destroyed on each iteration. That means that for do-while cycle the variable will always remain uninitialized, unless you introduce some rule that would somehow move the initialization to the beginning of the loop body. That would be quite confusing in my opinion.

提交回复
热议问题