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

后端 未结 10 1659
有刺的猬
有刺的猬 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 07:14

    int a;
    for(int b=0; b<10; ++b) { 
       int c;
    }
    

    scopes as if it were:

    int a;
    {
        int b=0;
    begin:
        if (b<= 10) 
        {
            {
                int c;
            }
            ++b;
            goto begin;
        }
    }
    

    The purpose is so that variables go out of scope at clearly defined sequence points.

提交回复
热议问题