4.1 — Blocks (compound statements) and local variables

Blocks (compound statements)

A block of statements, also called a compound statement, is a group of 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 any place where a single statement is allowed.

You have already seen an example of a block when writing the function main():

Blocks can be nested inside of other blocks. As you have seen, the if statement executes a single statement if the condition is true. However, because blocks can be used anywhere a single statement can, we can instead use a block of statements to make the if statement execute multiple statements if the condition is true!

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

3 is a positive number
Double this number is 6

Note that both statements inside the nested block executed when the if statement is true!

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

There is no practical limit to how many nested blocks you can have. However, it is generally a good idea to try to keep the number of nested blocks to at most 3 (maybe 4) blocks deep. If your function has a need for more, it’s probably time to break your function into multiple smaller functions!

Local variables

A variable’s scope determines who can see the variable, and how long it lives for. Variables declared inside a block are called local variables, and local variables have block scope (also called local scope). Variables with block scope can be accessed only within the block that they are declared in, and are destroyed as soon as the block ends. Consider this simple function:

Because nValue and dValue were declared inside the block that defines the main function, they are both destroyed when main() is finished executing.

Variables declared inside a block can only be seen within that block. Because each function has it’s own block, variables in one function can not be seen from another function:

Variables declared inside nested blocks are destroyed as soon as the inner block ends:

Nested blocks are considered part of the outer block in which they are defined. Consequently, variables declared in the outer block can be seen inside a nested block:

Note that variables inside nested blocks can have the same name as variable inside outer blocks. When this happens, the nested variable “hides” the outer variable:

This is generally something that should be avoided, as it is quite confusing!

Variables should be declared in the most limited scope in which they are used. For example, if a variable is only used within a nested block, it should be declared inside that nested block:

By limiting the scope of a variable, you reduce the complexity of the program because the number of active variables is reduced. Further, it makes it easier to see where variables are used. A variable declared inside a block can only be used within that block (or nested sub-blocks). This can make the program easier to understand.


Blocks allow multiple statements to be used wherever a single statement can normally be used.

Variables declared inside blocks are called local variables. These variables can only be accessed inside the block in which they are defined (or in a nested sub-block), and they are destroyed as soon as the block ends.

If a variable is only used in a single block, declare it within that block.

4.2 — Global variables
3.x — Comprehensive Quiz

18 comments to 4.1 — Blocks (compound statements) and local variables

  • 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 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.

  • 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.

  • Jason

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

  • 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.

  • 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?

    • 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.

  • Fluke

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

  • 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.

  • 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.

  • Zidane

    The best tutorials I’ve ever seen :P

  • 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;

  • buuface

    Hello can someone help me with this bit of code. I am trying to get the console to print “Zero is not a number” if the user enters 0, and “- is a negative number” is the number is negative. Please help!

    #include “stdafx.h”

    int main()
    using namespace std;
    cout <> nValue;

    if (nValue > 0)
    { // start of nested block
    if (nValue < 10)
    cout << nValue << " is between 0 and 10" << endl;
    cout << nValue << " is a positive number" << endl;
    cout << "Double this number is " << nValue * 2 << endl;
    } // end of nested block
    if (nValue = 0)
    cout << " Zero is not a fucking number!" << endl;
    if (nValue = 0)
    cout << " Zero is not a number!" << endl;
    cout << nValue << " is a negative number" << endl;
    cout << "double this number is " << nValue * 2 << endl;



Leave a Comment (Note: put C++ code inside [code][/code] brackets)




nineteen − ten =

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=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">