Search

4.11 — Compound statements and nested blocks

Compound statements

A compound statement (also called a block, or block of statements) is a group of zero or more statements that is treated by the compiler as if it were a single statement.

Blocks begin with a { symbol, end with a } symbol, and the statements to be executed are placed in between. Blocks can be used anywhere a single statement is allowed. No semicolon is needed at the end of a block.

You have already seen an example of blocks when writing functions:

Using blocks to execute multiple statements conditionally

By default, the statement conditionally executed by an if or else must be a single statement. However, by using a compound statement, we can instead conditionally execute multiple statements. To do so, we simply replace the single statement after the if and/or else with a compound statement.

Here’s an example of an if-else that uses a compound statement for both the if and else statements:

If the users enters the number 3, this program prints:

Enter an integer: 3
3 is a positive integer (or zero)
Double this number is 6

If the user enters the number -4, this program prints:

Enter an integer: -4
-4 is a negative integer
The positive of this number is 4

Nested blocks

Although functions can’t be nested inside other functions, blocks can be nested inside other blocks (as shown in the prior example).

The outermost block (typically the block defining the function body) is called the outer block. The block inside is typically called an inner block or nested block.

It is even possible to put blocks inside of blocks inside of blocks:

The maximum number of nested levels in a function is called the nesting depth of a function. For example, in the above function, there are 4 blocks total, but the nesting depth is 3 (because you can never go more than 3 blocks deep within the function).

C++ supports a nesting depth of 256 levels, which is far more than you’ll ever need. In fact, it’s a good idea to keep your nesting depth to 3 or less. Just as overly-long functions are good candidates for refactoring (breaking into smaller functions), overly-nested functions are also good candidates for refactoring.

Best practice

Keep the nesting depth of your functions to 3 or less (unless you have a compelling reason to do otherwise). If your function has a need for more, consider refactoring.


4.11 -- Chars
Index
4.10 -- Introduction to if statements