Difference between local scope and function scope

前端 未结 5 1787
独厮守ぢ
独厮守ぢ 2020-12-20 19:05

Once I assumed that these two have the same meaning but after reading more about it i\'m still not clear about the difference. Doesn\'t the local scope sometimes refer to sc

5条回答
  •  一整个雨季
    2020-12-20 19:35

    Doesn't the local scope sometimes refer to scope of function?

    Yes. In most C-derived languages, variables are valid in the scope in which they're declared. If you declare a variable inside a function, but not within any other code block, then that variable is usually called a "local" or "automatic" variable. You can refer to it anywhere in the function. On the other hand, if you declare your variable inside another code block -- say, in the body of a conditional statement, then the variable is valid only inside that block. Several other answers here give good examples.

    and what does it mean that only labels have a function scope?

    Context would be helpful, but it means that you can't jump from one function to a label in a different function.

    void foo(int a) {
        if (a == 0) goto here;  // okay -- 'here' is inside this function
        printf("a is not zero\n");
        goto there;             // not okay -- 'there' is not inside this function
    here:
        return;
    }
    
    void bar(int b) {
        if (b == 0) goto there; // okay -- 'there' is in this function
        printf("b is not zero\n");
    there:
        return;
    }
    

    Not to stir up a hornet's nest, but the scope of labels probably won't come up too often. Labels are mainly useful with the goto statement, which is needed only very rarely if ever, and even if you did choose to use goto you probably wouldn't even think of trying to jump into a different function.

提交回复
热议问题