CITS2002 Systems Programming  
next CITS2002 CITS2002 schedule  

The Hello World program in C++

Let's first consider the basic (anticipated) Hello World program written in C++.
As with many of the examples in this lecture, we will compare C++'s different features with equivalent ones of C11:

#include <iostream>

int main(void)
{
    std::cout << "Hello, world!\n"; 

    return 0;
}

Important points from this example:

  • #include <iostream>
    C++ source code is first passed through the same preprocessor as are C11 programs. Here, one of the standard C++ header files (with a similar role to C11's <stdio.h>) is included. Note that the C++ header file does not provide a filename suffix, and that the preprocessor will search a different set of directories to find the file. As much of C11's syntax is compatible with C++, we can also include (most) standard C11 header files.

  • std::cout << string;
    This statement outputs a text string (similar to C11) to a character output stream. The destination for the string is the std::cout stream, akin to stdout in C11. The << operator is not a bit-wise shift (as in C11), but indicating that the string is 'appended' to the stream.

  • What is std:: ?
    In C++, identifiers can be defined within a context, similar to a directory of identifiers, termed a namespace. When we want to access an identifier defined in a namespace, we tell the compiler to look for it in that namespace using the scope resolution operator (::). Here, we're telling the compiler to look for cout in the std namespace, in which many standard C++ identifiers are defined. A cleaner alternative is to use:

    using namespace std;

    This line tells the compiler that it should look in the std namespace for any identifier we haven't defined. We can omit the std:: prefix when writing cout.

 


CITS2002 Systems Programming, Lecture 23, p1, 17th October 2023.