Accelerated C++ Solution to Exercise 0-5

Exercise 0-5

Is this a valid program? Why or why not?

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


No. This is not a valid C++ program.

In C++ curly braces tell the implementation to treat whatever (statement) appears between them as a unit. This program would not work unless amended / corrected. The curly braces are missing.

For instance, running this (buggy) program we get this error in the build log.

error: expected initializer before ‘std’

To correct the program, simply add the curly braces and enclose the statements within these curly braces.

In addition, let’s add the return statement at the end for good practice. (The book mentions that the main function is the only function that does not require the return statement. Having a return statement in every single function that we define is however a good practice. So let’s do it!)

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


The program can now be compiled and run correctly. It produces the following in the console output window.

Hello World!

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


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

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

Leave a reply