Previous Page
Next Page

6.2. Block Statements

A compound statement, called a block for short, groups a number of statements and declarations together between braces to form a single statement:

{ [list of declarations and statements] }

Unlike simple statements, block statements are not terminated by a semicolon. A block is used wherever the syntax calls for a single statement, but the program's purpose requires several statements. For example, you can use a block statement in an if statement, or when more than one statement needs to be repeated in a loop:

{  double result = 0.0, x = 0.0;   // Declarations
   static long status = 0;
   extern int limit;

   ++x;                            // Statements
   if ( status == 0 )
   {                               // New block
      int i = 0;
      while ( status == 0 && i < limit )
      {  /* ... */  }              // Another block
   }
   else
   {  /* ... */  }                 // And yet another block
}

The declarations in a block are usually placed at the beginning, before any statements. However, C99 allows declarations to be placed anywhere.

Names declared within a block have block scope ; in other words, they are visible only from their declaration to the end of the block. Within that scope, such a declaration can also hide an object of the same name that was declared outside the block. The storage duration of automatic variables is likewise limited to the block in which they occur. This means that the storage space of a variable not declared as static or extern is automatically freed at the end of its block statement. For a full discussion of scope and storage duration, see Chapter 11.


Previous Page
Next Page