Accelerated C++ Solution to Exercise 0-6

Exercise 0-6

Is this a valid program? Why or why not?

#include <iostream>
int main() {{{{{{std::cout << "Hello World!" << std::endl;}}}}}}

Solution

Yes. This is a valid C++ program.

In C++ curly braces tell the implementation to treat whatever (statement) appears between them as a unit.

It is okay to have nested curly braces, as long as all the curly braces are balanced out. i.e. for every single open/left brace it is matched by a close/right brace.

Let’s run the program and see what we get?

Result

The program compiles okay. And gives us the following result in the console output window.

Hello World!

Process returned 0 (0x0)   execution time : 0.187 s
Press any key to continue.

Experiment – Nested Curly Braces

Let us, for curiosity sake to see if nested curly braces actually work? Here is a very simple program that I write for this experiment.

// Experiment with nested curly braces
#include <iostream>
int main()
{
    std::cout << "I am block 1" << std::endl;
    {
        std::cout << "I am block 1-1, son of block 1" << std::endl;
        {
            std::cout << "I am block 1-1-1, son of block 1-1, grandson of block 1." << std::endl;
            std::cout << "I am block 1-1-2, son of block 1-1, grandson of block 1." << std::endl;
        }
    }
    {
        std::cout << "I am block 1-2, son of block 1" << std::endl;
    }
}

The program compiles okay and gives us the followings in the console output window as expected.

I am block 1
I am block 1-1, son of block 1
I am block 1-1-1, son of block 1-1, grandson of block 1.
I am block 1-1-2, son of block 1-1, grandson of block 1.
I am block 1-2, son of block 1

Process returned 0 (0x0)   execution time : 0.187 s
Press any key to continue.

This experiment has demonstrated that nested curly braces essentially provides a way to group blocks of statements together, which I think is a very cool feature as it allows us breakdown tons of statements into smaller blocks. This is very handy if we are to define a chunky function.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

One thought on “Accelerated C++ Solution to Exercise 0-6”

Comments are closed.