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

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

    It would be very unnatural to have a declaration of i after the block and to then be able to access it in the block. Declaration in for and while are nice short-hands that give limited-scope use to a variable that is needed in the loop logic.

    Cleaner to do it this way:

    int i;
    do {
      i = get_data();
      // whatever you want to do with i;
    } while (i != 0);
    

提交回复
热议问题