Summary of Lifetime and Visibility

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at Summary of Lifetime and Visibility.

The following table is a summary of lifetime and visibility characteristics for most identifiers. The first three columns give the attributes that define lifetime and visibility. An identifier with the attributes given by the first three columns has the lifetime and visibility shown in the fourth and fifth columns. However, the table does not cover all possible cases. Refer to Storage Classes for more information.

Summary of Lifetime and Visibility

Attributes:

Level
ItemStorage-Class

Specifier
Result:

Lifetime
Visibility
File scopeVariable definitionstaticGlobalRemainder of source file in which it occurs
Variable declarationexternGlobalRemainder of source file in which it occurs
Function prototype or definitionstaticGlobalSingle source file
Function prototypeexternGlobalRemainder of source file
Block scopeVariable declarationexternGlobalBlock
Variable definitionstaticGlobalBlock
Variable definitionauto or registerLocalBlock

Description

The following example illustrates blocks, nesting, and visibility of variables:

Code

// Lifetime_and_Visibility.c  
  
#include <stdio.h>  
  
int i = 1;  // i defined at external level  
  
int main()  // main function defined at external level  
{  
    printf_s( "%d\n", i ); // Prints 1 (value of external level i)  
    {                                 // Begin first nested block  
        int i = 2, j = 3;          // i and j defined at internal level  
        printf_s( "%d %d\n", i, j );  // Prints 2, 3  
        {                             // Begin second nested block  
            int i = 0;                // i is redefined  
            printf_s( "%d %d\n", i, j ); // Prints 0, 3  
        }                             // End of second nested block  
        printf_s( "%d\n", i );        // Prints 2 (outer definition  
                                      //  restored)  
    }                                 // End of first nested block  
    printf_s( "%d\n", i );            // Prints 1 (external level  
                                      // definition restored)  
    return 0;  
}   

Comments

In this example, there are four levels of visibility: the external level and three block levels. The values are printed to the screen as noted in the comments following each statement.

Lifetime, Scope, Visibility, and Linkage

Show: