Navigation



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():

int main()
{ // start a block

    // multiple statements
    int nValue = 0;
    return 0;

} // end a block

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!

#include <iostream>

int main()
{
    using namespace std;
    cout << "Enter a number: ";
    int nValue;
    cin >> nValue;

    if (nValue > 0)
    { // start of nested block
        cout << nValue << " is a positive number" << endl;
        cout << "Double this number is " << nValue * 2 << endl;
    } // end of nested block
}

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:

int main()
{
    using namespace std;
    cout << "Enter a number: ";
    int nValue;
    cin >> nValue;

    if (nValue > 0)
    {
        if (nValue < 10)
        {
            cout << nValue << " is between 0 and 10" << endl;
        }
    }
}

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:

int main()
{ // start main block

    int nValue = 5; // nValue created here

    double dValue = 4.0; // dValue created here

    return 0;

} // nValue and dValue destroyed here

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:

void someFunction()
{
    int nValue;
}

int main()
{
    // nValue can not be seen inside this function.

    someFunction();

    // nValue still can not be seen inside this function.

    return 0;
}

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

int main()
{
    int nValue = 5;

    { // begin nested block
        double dValue = 4.0;
    } // dValue destroyed here

    // dValue can not be used here because it was already destroyed!

    return 0;
} // nValue destroyed here

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:

int main()
{ // start outer block
    using namespace std;

    int x = 5;

    { // start nested block
        int y = 7;
        // we can see both x and y from here
        cout << x << " + " << y << " = " << x + y;
    } // y destroyed here

    // y can not be used here because it was already destroyed!

    return 0;
} // x is destroyed here

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:

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;
} // outer nValue destroyed

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:

int main()
{
    // do not declare y here
    {
        // y is only used inside this block, so declare it here
        int y = 5;
        cout << y;
    }
    // otherwise y could still be used here
}

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.

Summary

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
Index
3.x — Comprehensive Quiz

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

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

  • [...] 2007 Prev/Next Posts « 3.7 — Converting between binary and decimal | Home | 4.1 — Blocks (compound statements) and local variables » Sunday, June 17th, 2007 at 1:12 [...]

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

  • 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.
    Thanks,
    Andrew

  • [...] 4.1 — Blocks (compound statements) and local variables [...]

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

  • [...] a { } block, it cannot be seen or changed from outside that block. (T). gi?i thích: (xem them: http://www.learncpp.com/cpp-tutorial/41-blocks-compound-statements-and-local-variables/) int main() { int nValue = [...]

  • Zidane

    The best tutorials I’ve ever seen :P

You must be logged in to post a comment.