Search

6.1 — Compound statements (blocks)

A compound statement (also called a block, or block statement) 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, with the statements to be executed being 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, as the function body is a block:

Blocks inside other blocks

Although functions can’t be nested inside other functions, blocks can be nested inside other blocks:

When blocks are nested, the enclosing block is typically called the outer block and the enclosed block is called the inner block or nested block.

Using blocks to execute multiple statements conditionally

One of the most common use cases for blocks is in conjunction with if statements. By default, an if statement executes a single statement if the condition evaluates to true. However, we can replace this single statement with a block of statements if we want multiple statements to execute when the condition evaluates to true.

For example:

If the user 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

Block nesting levels

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

The nesting level (also called the nesting depth) of a function is the maximum number of nested blocks you can be inside at any point in the function (including the outer block). In the above function, there are 4 blocks, but the nesting level is 3 since in this program you can never be inside more than 3 blocks at any point.

The C++ standard says that C++ compilers should support 256 levels of nesting -- however not all do (e.g. as of the time of writing, Visual Studio supports somewhere between 100 and 110).

Despite what C++ technically supports, it’s a good idea to keep your nesting level to 3 or less. Just as overly-long functions are good candidates for refactoring (breaking into smaller functions), overly-nested functions are hard to read and are good candidates for refactoring (with the most-nested blocks becoming separate functions).

Best practice

Keep the nesting level of your functions to 3 or less. If your function has a need for more nested levels, consider refactoring your function into sub-functions.


6.2 -- User-defined namespaces and the scope resolution operator
Index
O.4 -- Converting between binary and decimal

16 comments to 6.1 — Compound statements (blocks)

  • papagym177

    This codes (comments)are confusing and should be clearified. But the outer (int nValue =5;) could sill be used AFTER the nested block if you wanted to use it, Y/N ? I can understand there are two nValue's in the code. Thank You.

    int main() { // outer block int nValue = 5; if (nValue >= 5) { // nested block int nValue = 10; // nValue now refers to the nested block nValue. // the outer block nValue is hidden } // nested nValue destroyed // nValue now refers to the outer block nValue return 0;

  • Zidane

    The best tutorials I've ever seen :P

  • posentel

    It may be helpful to point out that since a block replaces a single statement (that ends with a semicolon), the block supercedes the use of a semicolon. No semicolon is necessary to end a block.

  • Andrew

    Having more review questions and quizes would help me more. The more I get into these lessons the less I know how to use things in the same program. More examples or quizes might be worth looking into.
    Thanks,
    Andrew

  • Fluke

    Now i see a benefit from declare_variable_when_needed instead of all at the top of the function.
    Cheers :)

  • davidv

    Hi Alex,

    Fabulous work, first of all.

    I have a question: how does "using namespace std" work with the nesting? It seems that once written in a block, it is valid for the sub-blocks as well. If it is so, wouldn't it be easier to simply declare it at the beginning rather than several times inside functions?
    Thanks.

    • As you note, the using statement normal variable scoping rules -- if used inside a block, it applies to the block and all subblocks.

      Whether you put it in each function or declare it globally so it affects your entire program is really a personal choice. Doing it globally tends to be more convenient, but also increases the potential for naming collisions.

  • learning c++

    Hey Alex when you read this would like to suggest adding something like a review at the end of every section just quickly reminding people like for example on the variables section 1 it would say all the variable types with quick meanings and examples maybe.

  • Jason

    A downloadable version of the tutorial would be fire! I know, I know, I can save the web pages manually. :)

  • Steven, please repost your code in my forums. WordPress/HTML ate what you posted and it was pretty indecipherable.

    cin works for both numbers and strings. In your case, I think using cin to read strings into a temporary buffer would work great. Once the user has entered a string, you could then send it to whomever it's supposed to go to. I talk more about strings in section 6.6.

    The "next section" link is a good idea. It will take a while to implement because I'll have to edit each page manually.

    As for a printable version of the whole site, I don't think that is currently possible using this software. So for the time being, at least, you will have to continue to view things lesson by lesson.

    • Ralph

      Maybe not the whole site as one, but each section having a printer friendly version would be awesome, I'm currently copy/pasting important stuff and printing it, and note taking though because I find it useful, but I would find a printable version very useful for certain lessons as I need to open up the page source and edit it to make it printer friendly at the moment.

      • Hmmm, I had installed a plugin that let users do that, but I think it may have stopped working when I upgraded to a newer version of WordPress. I'll have to see if there's an update. However, I'm right in the middle of a relocation, so it'll probably take me a while to get to it. My apologies.

        • ramakanth

          The tutorials are truly ememplary.It gets the basics right.
          Please let me know if there is a downloadable version(.pdf) of this
          site as it would be quite useful.

  • Steven H.

    [ Mangled code removed ]

    I made this calculator using visual c and was wondering if there was any way to shorten this code. It's really long for just a simple calculator!

    Also, even though I haven't finished the tutorial yet I was wondering what could I use to "cin" multiple characters or numbers into a program? All cin is good for is numbers, and all char can be used for is single characters. I want to eventually make like a virtual AIM kind of thing (i'm stressing the word "eventually").

    I really like your tutorial and took it over cplusplus.com. You should include a "next section" link at the end of each tutorial page though, so you don't have to go back to the table of contents to move on.

    Oh ya I forgot to mention you should add a printable version of the whole tutorial to the site, it would make it a lot easier and would save ink and paper.

    Thank you,
    Steven H.

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">