Scope

From cppreference.com
< c‎ | language

Scope determines the region of program text within which an identifier is visible, that is where the identifier can be used. When an identifier designates more than one entity, the different entities either have different scopes or are in different name spaces.

C has four kinds of scopes:

  • function scope
  • file scope
  • block scope
  • function prototype scope

A function prototype is a declaration of a function that declares the types of its parameters.

A label name is the only kind of identifier that has function scope. Using a label name may occur (in a goto statement) anywhere in the function in which the label name appears. The syntactic appearance of a label name, that is a name followed by a colon (:) and a statement, implicitly declares the label name.

For all other identifiers, placement of an identifier's declaration (in a declarator or type specifier) determines the scope of that identifier.

If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit.

If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block.

If the declarator or type specifier that declares the identifier appears within the list of parameter declarations in a function prototype (not part of a function definition), the identifier has function prototype scope, which terminates at the end of the function declarator.

If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

[edit] Example

Overlapping scopes

#include <stdio.h>
 
int main(void)
{
    int a = 1;
    {
     int a = 2;          /* inner declaration hides outer declaration */
     printf("%d\n", a);
    }
    printf("%d\n", a);   /* outer declaration is visible again        */
 
    return 0;
}

Possible output:

2
1