Home

Block Statement

C++ is a block structured programming language. A block is a sequence of definitions and/or statements inside a pair of brace characters: { denotes the beginning of a block and should be read as begin and } denotes the end of a block and should be read as end. Blocks can be nested and a block can almost always be substituted for a single statement.

The beginning brace chracter can follow something prior on the same line (One True Brace Style) or can be placed on a new line (Allman Style). I will always use the more readable Allman Style with two space indentation.

Unfortunately, C++ uses braces for at least four distinctly different purposes: function blocks, class/structure/union blocks, block statements, and compound expression blocks. The interactions between blocks and semicolons are inconsistent and frustrating:

void setup(void)
// Function block, NOT followed by a semicolon:
{
  // Function blocks can define variables that are private to that block:
  int x;

  // Block statement, not normally followed by a semicolon:
  {
    // Block statements can define variables that are private to that block:
    int x; // private variable, HIDES int x above!
    DoSomething();
  }

  // Block statement, followed by an unnecessary semicolon:
  {
    int x; // private variable, HIDES int x above!
    DoSomething();
  };

  // structure definition (class and union are similar), always
  // followed by a semicolon:

  struct Foo
  {
    bool x;
    int y;
    float z;
  };

  // structure TYPE definition (class and union are similar), always
  // followed by a semicolon after the type name:

  typedef struct
  {
    bool x;
    int y;
    float z;
  } Foo;

  // structure VARIABLE definition, always followed by a semicolon
  // after the variable name:

  struct
  {
    bool x;
    int y;
    float z;
  } Foo;

  // Compound expression block, always followed by a semicolon:
  int y[5] = { 1, 2, 3, 4, 5 };
}

Home


Questions or comments to phil@munts.net