Compound Statement (Blocks)


Syntax


compound_statement:
 { statement_list }
 
statement_list:
        statement
        statement_list statement

Notes

In C++, braces may be used to group several statements together so that they may be treated as a single statement (block). For example, one possible syntax of the if statement is:

if (expression)
 statement

where statement represents a single statement. Thus, if multiple statements are to be supplied as the consequent of the conditional then they must be blocked together, as the example below demonstrates.

int i=0;
int j=0;
if (i == j)
 {
  i =+ 1;
  j =+ 2;
 }

The same technique applies to some of the other program flow control statements. A block can be entered any time, not just in connection with program flow control statements. Entering a block implies that a new scope is created. Consider the following example.

int i=0;
int k=0;
{
 i++;     // Outer scope is visible within block.
 int k=1; // Hides k of outer scope
 k++;     // Increments k of inner scope
 int j=2; // Declares variable local to block
}
i++;      // This is ok because i is defined outside the inner block.
j++;      // Causes a syntax error because j is defined within the inner block.

Unless defined elsewhere, j is not known outside the block in which it is defined; therefore, attempting to reference the variable j below the block causes the compiler to flag a syntax error. An inner block can reference the definitions of its containing blocks; hence, it is quite valid to increment the variable i in the inner block. Declaring a variable whose name is the same as that of a variable in an outer scope causes the name from the outer scope to be hidden (as for the variable k in the above example).

For an example of where blocks must be used to avoid problems with bypassing initialization, see the documentation for the switch statement.