What is the scope of a 'while' and 'for' loop?

后端 未结 10 1668
有刺的猬
有刺的猬 2020-11-30 06:37

What is the scope of a while and for loop?

For example, if I declared an object within the loop, what is its behavior and why?

10条回答
  •  不知归路
    2020-11-30 06:58

    Anything declared in the loop is scoped to that loop and cannot be accessed outside the curly braces. In fact, you don't even need a loop to create a new scope. You can do something like:

    {
       int x = 1;
    }
    
    //x cannot be accessed here.
    

提交回复
热议问题