Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between local scope and function scope

Tags:

c++

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?

like image 710
user103214 Avatar asked Oct 28 '11 19:10

user103214


2 Answers

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 */
}
like image 155
Alok Save Avatar answered Sep 20 '22 07:09

Alok Save


Local scope is the area between an { and it's closing }. Function scope is the area between the opening { of a function and its closing }, which may contain more "local" scopes. A label is visible in the entirety of the function within which it is defined, e.g.

int f( int a ) 
{
    int b = 8;
    if ( a > 14 )
    {
       int c = 50;
       label:
       return c - a - b;
    }
    if ( a > 7 ) goto label;
    return -99;
}

int c is not visible outside its enclosing block. label is visible outside its enclosing block, but only to function scope.

like image 30
Rob K Avatar answered Sep 18 '22 07:09

Rob K