复合语句 (C)Compound Statement (C)

复合语句(也称为“块”)通常显示为另一个语句(例如 if 语句)的主体。A compound statement (also called a "block") typically appears as the body of another statement, such as the if statement. 声明和类型描述可在复合语句的头部出现的声明的格式和含义。Declarations and Types describes the form and meaning of the declarations that can appear at the head of a compound statement.

语法Syntax

compound-statement:compound-statement:
{ declaration-list optstatement-listopt}{ declaration-list optstatement-listopt}

declaration-list:declaration-list:
declarationdeclaration

declaration-list declarationdeclaration-list declaration

statement-list:statement-list:
statementstatement

statement-list statementstatement-list statement

如果有声明,则它们必须在任何语句之前出现。If there are declarations, they must come before any statements. 在复合语句开头声明的每个标识符的范围从其声明点扩展到块的末尾。The scope of each identifier declared at the beginning of a compound statement extends from its declaration point to the end of the block. 它在整个块中都可见,除非内部块中存在对同一标识符的声明。It is visible throughout the block unless a declaration of the same identifier exists in an inner block.

复合语句中的标识符将假定 auto,除非另使用 register、static 或 extern(只能是 extern 的函数除外)显式声明。Identifiers in a compound statement are presumed auto unless explicitly declared otherwise with register, static, or extern, except functions, which can only be extern. 您可停止在函数声明中使用 extern 说明符,但函数仍然是 externYou can leave off the extern specifier in function declarations and the function will still be extern.

如果在具有存储类 extern 的复合语句中声明了变量或函数,则将不会分配存储并且不会执行初始化。Storage is not allocated and initialization is not permitted if a variable or function is declared in a compound statement with storage class extern. 声明引用在其他位置定义的外部变量或函数。The declaration refers to an external variable or function defined elsewhere.

每当进入复合语句时,将重新分配并初始化(如有必要)在块中使用 auto 或 register 声明的变量。Variables declared in a block with the auto or register keyword are reallocated and, if necessary, initialized each time the compound statement is entered. 在退出复合语句后将不再定义这些变量。These variables are not defined after the compound statement is exited. 如果在块内声明的变量具有 static 特性,则将在程序开始执行时初始化变量并在整个程序中保留变量值。If a variable declared inside a block has the static attribute, the variable is initialized when program execution begins and keeps its value throughout the program. 有关 static 的信息,请参阅存储类See Storage Classes for information about static.

此示例演示了一个复合语句:This example illustrates a compound statement:

if ( i > 0 )   
{  
    line[i] = x;  
    x++;  
    i--;  
}  

在此示例中,如果 i 大于 0,则复合语句内的所有语句将按顺序执行。In this example, if i is greater than 0, all statements inside the compound statement are executed in order.

另请参阅See Also

语句Statements