Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

c++ - Difference between local scope and function scope

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 scope of function? and what does it mean that only labels have a function scope?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
void doSomething()
{                                    <-------
     {                   <----               | 
                              |              |
         int a;           Local Scope    Function Scope
                              |              |
     }                   <----               | 
}                                    <------- 

Function Scope is between outer { }.

Local scope is between inner { }

Note that, any scope created by {``} can be called as the local scope while the {``} at the beginning of the function body create the Function scope.
So, Sometimes a Local Scope can be same as Function Scope.

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

Labels are nothing but identifiers followed by a colon. Labeled statements are used as targets for goto statements. Labels can be used anywhere in the function in which they appear, but cannot be referenced outside the function body. Hence they are said to have Function Scope.

Code Example:

int doSomething(int x, int y, int z)
{
     label:  x += (y + z);   /*  label has function scope*/
     if (x > 1) 
         goto label;
}

int doSomethingMore(int a, int b, int c)
{
     if (a > 1) 
         goto label; /*  illegal jump to undefined label */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...