生存期和可见性的摘要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
Item 存储类Storage-Class

说明符Specifier
结果:Result:

生存期Lifetime
可见性Visibility
文件范围File scope 变量定义Variable definition staticstatic GlobalGlobal 此项所在的源文件的剩余部分Remainder of source file in which it occurs
变量声明Variable declaration extern GlobalGlobal 此项所在的源文件的剩余部分Remainder of source file in which it occurs
函数原型或定义Function prototype or definition staticstatic GlobalGlobal 单个源文件Single source file
函数原型Function prototype extern GlobalGlobal 源文件的剩余部分Remainder of source file
块范围Block scope 变量声明Variable declaration extern GlobalGlobal Block
变量定义Variable definition staticstatic GlobalGlobal Block
变量定义Variable definition auto 或 registerauto or register 本地Local Block

示例Example

描述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.

另请参阅See Also

生存期、范围、可见性和链接Lifetime, Scope, Visibility, and Linkage