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 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 you can never be inside more than 3 blocks at any point.

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 also 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, consider refactoring.

6.2 -- User-defined namespaces
O.4 -- Converting between binary and decimal

64 comments to 6.1 — Compound statements (blocks)

  • Wow! Thank you! I continually wanted to write on my site something like that. Can I take a fragment of your post to my blog?

  • Tony

    Now I got some doubts. Is there any need for nested blocks at all?
    Cannot this code:

    be just written as:

    To me the first one seems harder to read, and not necessary, but perhaps there's a reason to use these blocks? Thanks @nascardriver!

  • Shivu

    Can someone pls tell me why the getNumber function doesn't work? Because regardless of what number I enter my code is considering that I have entered 0 only, per its initialization. It disregards the getNumber function.

    • nascardriver

      You're ignoring the return value of `getNumber` and aren't using the argument passed to `getNumber`. See lesson 2.2 and 2.3.

    • The Yellow Prince

      Plus, functions do not directly affect variables declared in main() without some extra syntax. When you use a variable from main as an argument in a function it copies the value in that variable to the parameter and uses that. In this instance, the value held by x is being passed to the function, not x itself, so x remains unaffected. Your function assigns the input to its parameter "value", which is destroyed when the function ends. You would want to have something like "x = getNumber(x);" to have it work as I assume you've intended it to.

  • I will right away grab your rss as I can not find your email subscription link or e-newsletter service. Do you have any? Please let me know in order that I could subscribe. Thanks.

  • Function cant nested function but block can nested block, but isn't int main() <-- is also a function? How to define what is block and what is function?

    • Keshav

      Take int main it starts with a block and ends with a can keep as many blocks into it as you wish but after the block of the main block(outer block) has been closed you will have to add another function or end the program

  • You could definitely see your expertise in the paintings you write. The arena hopes for even more passionate writers like you who aren't afraid to mention how they believe. All the time go after your heart.

  • sami

    "... overly-nested functions are also good candidates for refactoring (with the most-nested blocks becoming separate functions)."

    Is the most-nested block in the code example below,  the third block (  if-else ) ?

  • koe

    "We’ll talk more about if statements, including the use of blocks, in lesson 5.2 -- If statements."

    No longer accurate. Lesson 5.2 is before this lesson, and doesn't talk about blocks.

  • Benur21

    Can I use compound statements alone, outside any if, function, etc?

    • Yes.
      If you think you need to do this to make your code more tidy, use a function instead.

      • Charan

        But doesn't it raise the concerns about scope of a variable as shown in one of the comments.(Copying the code from @Alireza's comment)
        int main()
            int a = 0;
            std::cout << a ;

                int a = 1;
                std::cout << a;

                     int a = 2;
                     std::cout << a;
            std::cout << a;
            return 0;

        • nascardriver

          I don't understand what you're getting at. Alireza's code can be re-written with functions and without shadowing (see Alex's answer to Alireza's comment).

  • Aakash

    "It is even possible to put blocks inside of blocks inside of blocks:" can be changed to
    "It is even possible to put blocks inside block:"

  • Alireza


    In the following program:


    @a doesn't work similarly @a at the 2nd block and 3rd block. When should we use blocks like this way ?

    • Alex

      the 2nd and 3rd nested blocks shadow the outer block a, so your code actually runs identically to this program:

      > When should we use blocks like this way ?

      Never. :) Just because you can do something doesn't mean you should.

  • Aditi


    In the third program , what result would we get if we enter a negative integer ? Who don’t we have an else statement for negative integers ? Also , isn’t it necessary that every if statement needs to be followed by an else statement ?

    • Aditi

      I think the reason is because as we have taken data type as int, which is already unsigned and accepts only positive integral values. But if we had already specified the data type earlier , why did we need an If statement for accepting only positive numbers? Even if we did not have an if statement for accepting positive integral values , and the user entered a negative number , wouldn’t we get an error in either case ?

    • nascardriver

      Hi Aditi!

      > what result would we get if we enter a negative integer
      No output

      > isn’t it necessary that every if statement needs to be followed by an else statement
      No, you don't need an else-statement

      > we have taken data type as int, which is already unsigned
      An int is signed by default

      Run the program yourself, play around with some numbers and place breakpoints to get a better understanding of what's happening.

  • Ali Dahud

    Hi Alex!

    could you go through my code and correct the mistakes i made?
    oh and please explain this piece:
            tempNum = larger;
            larger = smaller;
            smaller = tempNum;

    • nascardriver

      Hi Ali!

      I've added comments addressing the issue with your code.
      Try correcting it and post your progress, if you have any questions feel free to ask.

      > please explain this piece
      It's swapping the values of @larger and @smaller. Imagine you have three baskets in front of you, one contains a red apple, one contains a green apple and one is empty.
      You want the red apple to be in the green apple's basket and the green apple to be in the red apple's basket.
      You are only allowed to hold one apple at a time.

      PS: Please post your code in the corresponding lesson next time, this quiz is in lesson 4.1a

      • Ali Dahud

        isn't that some kind of sorting?

        • nascardriver

          No it's not, you only want two elements to change places.

          EDIT: Well, technically, it might be sorting since you now have two elements in a specific order, but I would call it sorting when it's just two elements and not even a list/array.

          • Ali Dahud

            i remember the bubble sorting used a method like this. or at least some kind of like this

            • Alex

              Yes, many sorting methods work by swapping elements until the list of items is sorted. Bubble sort swaps adjacent elements. Selection sort swaps once per iteration.

              Generally, when we transpose the value of two elements, we call it a swap. We call it a sort when we put all the elements in a list or array into some sorted order.

              • Ali Dahud

                Hi Alex, how many tutorials do you recommeend me on reading daily?

                • Alex

                  I don't have a recommendation on this.

                  It really depends entirely on your learning capability, motivation, and how much time you want to spend experimenting with each topic on your own.

              • i have the time to read as much as i want and my learning capability is pretty big i guess. with each topic i guess 20 minutes-1 hour or 1,5 hour depending if it has coding quizzes in it. so how  much should i read? oh and i lack motivation i guess so how should i motivate myself? for example i start watching videos, news while im supposed to learn.

    • > in the ifElse  function there's no need to return tempNum you can return larger either. And Its good to initialize tempNum directly above where you do swapping.
      > ifElse returns something and you are not storing it. If you don't want to, change the functions type to void.

  • Amir

    Hi Alex. The Output of the first program has a mistake!

    This is the code :

    below it we have this output :

       Enter an integer: 3
       3 is a positive integer
       Double this number is 6

    I guess it should be like this :

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

    Thank You! : ))

  • Nick

    Thank you so much for making all these.

    On the 2ed code example if you put in 0 won't it fail when it gets to

  • Jack Oz

    Alex thank you so much your time, you help many people. Are you familiar with socket programming in C++?

    Best regards,

  • Rajeg

    Hey Alex,

    maybe you should add a special case for 0 on your second program, now it says that 0 is a negative integer.

  • Jim


    On line 18 of the second program you have:
    cout << "The positive of this number is " << -value << endl;.

    Since you entered -4 for the input, how does the program know to print out 4 (positive)? when no math is ever done?

    Does this somehow say take value and multiply it times -1 ?
    In math we learned (-4 * -1)= 4.

  • Mr D

    In the last code example above, you're missing a semi-colon at the end of the line(4):

  • techsavvy....aye

    A minor note in the last program
    it should be just value instead of nValue shouldn't it?
    In block inside of block inside of block!

  • Todd


    I would change the title,

    "4.1 — Blocks (compound statements) and local variables"

    to the title referenced on your main page

    "4.1 — Blocks (compound statements)"

    since you don't talk about local variables here.

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

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

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

Leave a Comment

Put all code inside code tags: [code]your code here[/code]