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

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

    This is because everything else follows the practice of declaring variables before you use them, eg:

    public static void main(String[] args){ 
      // scope of args
    }
    
    for(int i=1; i<10; i++){
      // scope of i
    }
    
    
    {
    ...
    int somevar;
    //begin scope of var
    
    ...
    
    //end of scope of var
    }
    

    This is because things are parsed top down, and because following this convention keeps things intuitive, thus why you can declare a while(int var < 10) because the scope of that var will be the area inside the loop, after the declaration.

    The do while doesn't make any sense to declare a variable because the scope would end at the same time it would be checked because that's when that block is finished.

提交回复
热议问题