A block statement, or compound statement, lets you group any number of data definitions, declarations, and statements into one statement. All definitions, declarations, and statements enclosed within a single set of braces are treated as a single statement. You can use a block wherever a single statement is allowed.
A block statement has the form:
.----------------------------------. .---------------. V | V | >>-{----+------------------------------+-+----+-----------+-+--}->< +-type_definition--------------+ '-statement-' +-file_scope_data_declaration--+ '-block_scope_data_declaration-'
At the C89 language level, definitions and declarations must precede any
statements.
For C at the C99 language level and for Standard C++ and C++98, declarations and definitions can appear anywhere, mixed in with other code.
A block defines a local scope. If a data object is usable within a block and its identifier is not redefined, all nested blocks can use that data object.
Example of Blocks
The following program shows how the values of data objects change in nested blocks:
/** ** This example shows how data objects change in nested blocks. **/ #include <stdio.h> int main(void) { int x = 1; /* Initialize x to 1 */ int y = 3; if (y > 0) { int x = 2; /* Initialize x to 2 */ printf("second x = %4d\n", x); } printf("first x = %4d\n", x); return(0); }
The program produces the following output:
second x = 2 first x = 1
Two variables named x are defined in main. The first definition of x retains storage while main is running. However, because the second definition of x occurs within a nested block, printf("second x = %4d\n", x); recognizes x as the variable defined on the previous line. Because printf("first x = %4d\n", x); is not part of the nested block, x is recognized as the first definition of x.
Related References