Hello World (C Plus Plus)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Ada | ALGOL 68 | Alice ML | Amiga E | Applescript | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | Clojure | C++ | C# | Delphi | Dylan | E | Eiffel | Erlang | Forth | FORTRAN | Fortress | Go | Groovy | Haskell | Hume | IBM PC bootstrap | Inform 7 | Java | Java, Swing | JavaScript | LaTeX | Lisp | Logo | Lua | Maple | MATLAB | Mercury | OCaml/F Sharp | occam | Oz | Pascal | Perl | PHP | Pic | PIR | PLI | PostScript | Prolog | Python | Rexx | Ruby | Scala | Scheme | Seed7 | sh | Smalltalk | SQL | Standard ML | SVG | Tcl | Tcl Tk | Visual Basic | Visual Basic .NET | XSL

This simple C++ program prints a message to the screen and then exits.

The standard Hello World program

In C++, access to standard functions, classes, objects etc. is given through including standard headers. Those standard headers are simply text files containing all necessary definitions. The includes are traditionally done at the beginning of a file, before anything is defined in the program itself. Thus the general structure of the program looks like the following.

<<hello_world.cpp>>=
includes
definitions

Every C++ program has to define the function main. This function is executed when you run the program. In the simplest case (which we use here), it does not take any arguments, and gives back an integer value telling if the program completed its task successfully. The main function looks like this:

<<definitions>>=
int main()
{
  statements
}

The first statement outputs "Hello World!". The object cout is the console standard output stream, the operator "<<" outputs data to that stream, and the header file "iostream" contains the declaration for cout. The "std" part of std::cout is a namespace specifying that the cout object belongs to the standard library. The "\n" is C++'s way to denote a line end. Note that this is not platform dependent; the library is required to translate \n into whatever is required by the platform for a line end (e.g. on Windows, it will cause output of a CR-LF pair).

<<statements>>=
std::cout << "Hello World!\n";

To use the object std::cout, the header iostreams is needed, thus it has to be included at the beginning of the program:

<<includes>>=
#include <iostream>

After the output, the program reports successful termination by returning 0 from main, which means success.

<<statements>>=
return 0;

Note that C++ allows to omit this last statement; If main ends without return, it's equivalent to return 0; at the end of main.

An improved version with error checking

Actually, the program as written above is a bit sloppy. It simply assumes that writing "Hello World" succeeds. However while it is quite unlikely that it would fail, it's not unthinkable. For example, the caller could have redirected standard output to a file located at another computer, and just while writing the text, the connection to that computer might fail. In that case, the program as written above will still report success. Thus here comes an improved version with error handling.

The general structure of improved program is, of course, the same:

<<improved_hello_world.cpp>>=
includes of improved hello world
definitions of improved hello world

Of course, the header iostream will be needed again.

<<includes of improved hello world>>=
#include <iostream>

The main function of course still first outputs "Hello World!", but instead of just indicating success, it checks and reports errors.

<<definitions of improved hello world>>=
int main()
{
  std::cout << "Hello World!\n";
  if (output failed)
  {
    report error
  }
  else
  {
    report success
  }
}

The object std::cout stores if any output to it failed, and thus we can just query it for failure:

<<output failed>>=
std::cout.fail()

Now, how do we report an error? It would be nice to print an error message to the user. But we can't just print it to std::cout, because after all, that just failed. Also, even if the user redirected output, he probably wants to see the error message on the screen. Therefore there's another object corresponding to standard error output: std::cerr.

<<report error>>=
std::cerr << "Sorry, greeting failed.\n";

We don't check for output failure here, because if this also fails, we cannot do anything useful anyway.

Now we have to terminate the program. Of course we should not report success now, because while the user (probably) has seen the message, the return code might still be used by another program, which of course cannot understand our error message. For this case, the C++ standard defines a constant EXIT_FAILURE, which, when returned, indicates failure.

<<report error>>=
return EXIT_FAILURE;

The constant EXIT_FAILURE is define in the standard header cstdlib, thus it must be included as well:

<<includes of improved hello world>>=
#include <cstdlib>

If the output was successful, we don't print any extra message, but just use a return code to indicate success. We already know that we can use return 0; for that, but since cstdlib is included anyway, we also can make use of another symbolic constant defined here: EXIT_SUCESS. Returning EXIT_SUCCESS is equivalent to returning 0 (indeed, usually EXIT_SUCCESS is defined to the value 0), but more clearly indicates to the reader of the code what it means.

<<report success>>=
return EXIT_SUCCESS;
Download code
Views
Personal tools