Accelerated C++ Solution to Exercise 0-0

Exercise 0-0

Compile and run the Hello World program.

Solution

The classic Hello World code looks like this.

// a small C++ program</p>

#include <iostream>

int main()
{
    ( (std::cout << "Hello, world!") << std::endl);
    return 0;
}

In detail

// a small C++ program
  • The double forward slashes indicates comment. Comments are ignored by the program during implementation.
<br />#include <iostream>

  • The #include directive ensures the <iostream> (input-output stream) facility is made available to the program.
int main()
{
}
  • We declare that the main function would yield an integer (int) type result. (i.e. result = 0 if success. Otherwise non-zero). The main function is the first function that is run when we implement a C++ program – so we must define one.
  • We define the main function within the two curly braces { }.
    ( (std::cout << "Hello, world!") << std::endl);
  • The expression statement create a result of type std::ostream (standard output stream), defined by its first operand std::cout (standard console output). The utility cout (console output) is in the (namespace) scope std (standard library).
  • The first (left associative) output operator << writes the string literal “Hello, world” to the std::cout. This causes a side-effect of displaying the string literal on the console command window.
  • The second (left associative) output operator << allows the manipulator std::endl (standard end line) to manipulate the standard output stream, which in this case, ends the current line of output.
  • Note that the brackets are not strictly required. I’ve included the brackets here purely to help visualising the logics associating with the left-associative output operator << .
  • The entire expression statement yields std::cout as a value (a result) which is of type std::ostream (standard output stream), and as a side effect writes the string literal (Hello, World!) onto this standard output stream (as displayed in the output command window). The std::endl manipulator ends the output line. Once it’s displayed (which is what we wanted), the semi-colon at the end of the expression statement discards the std::cout value (which is appropriate as we don’t need to keep hold of this value any more).
    return 0;
  • The return statement explicitly return an integer (int) value of 0 at the end of the main function to imply job run success. The semi-colon explicitly states that this is the end of this return statement.

Result

Once submitted the program, the following text appears in command window as expected.

Hello, world! 

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

Reference

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

3 thoughts on “Accelerated C++ Solution to Exercise 0-0”

    1. A WordPress plugin update had broken the syntax sometime ago! I’ve just done a one-off fix. Thanks for spotting :)

Comments are closed.