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

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

    Add this

    #define do(cond) switch (cond) do default:
    

    at the beginning of your code.

    Now, you can write

    do (int i = get_data()) 
    {
    
        // your code
    
    } while ((i = get_data()));
    

    It is important that this #define does not break the original syntax of the do keyword in do-while loop.

    However, I admit that it is obscure.

提交回复
热议问题