5D. Compound Statements and Scope


Compound statements

In several places, C++ requires you to write one statement. But what if you want to write more than one statement? Then you package those statements into a single compound statement.

Compound statements

A compound statement begins with a left brace and ends with a right brace. In between the braces are zero or more statements, one after the other. For example,

  {
    x = 2;
    y = 0;
  }
is a compound statement that sets x = 2 and y = 0.


Layout

Layout refers to issues such as where you break lines and how much you indent lines. Since C++ is free-form, how to lay out a program is up to the programmer. There is a variety of conventions for laying out a compound statement, but the coding standards for this course require you to use one style.

  1. Each left brace must have a matching right brace directly below it (in the same column).

  2. There must be no characters on or to the left of the line segment between a left brace and the matching right brace. Indent the body of the compound statement.

  3. Choose an amount to indent, and stick with it. Indent at least two spaces and no more than four spaces.

  4. A compound statement is allowed to contain no statements. In that case, you can write {}.



Scope

Each variable has a scope, which is the part of the program where the variable can be used directly, by writing its name.

Any variable that is declared inside a compound statement can only be used from the point where it is declared to the end of the compound statement.

Nested compound statements and shadowing

You can write one compound statement inside another. A variable's scope is limited by the smallest compound statement that contains the variable's declaration.

For example, in

  {
    int r = 0;
    {
      int s = r + 1;
      
    }
    int q = 2*r;
  }
variable s can only be used inside the inner compound statement.


Shadowing

Suppose that compound statement B is inside compound statement A. C++ allows you to declare a variable in B that has the same name as one that is declared in A. For example,

  {
    int p, q, x = 5;
    {
      int x = 9;
      p = x;
    }
    q = x;
  }
makes p = 9 and q = 5. There are two different variables, each called x. Statement p = x uses the variable x whose scope is the inner compound statement. Since that variable does not exist outside of the inner compound statement, statement q = x uses the variable x declared in the outer compound statement.

As you can see, shadowing can be confusing. The coding standards for this course require you not to use shadowing.



Exercises