Skip to main content

1.3) Your First C++ Program: Alternative Version


The "Hello World!" program can also be written like this:

#include <iostream>
using namespace std;
int main()
{
  cout << "Hello World!" << endl;
  return 0;
}

Notice that the std:: prefix is gone from cout and endl, and that using namespace std; now appears before the main function.

std is the 'standard namespace', within which the names of the various elements of the C++ standard library are defined. This namespace 'protects' the names of standard library elements, allowing us to avoid clashes with the names of other things used in a program. However, if you use standard library elements frequently, typing the std:: prefix quickly becomes tedious.

Line 3 of this code declares that we wish to 'use' the namespace and thus omit the prefix, allowing us to use cout and endl instead of std::cout and std::endl on subsequent lines.

A using namespace declaration makes writing the code easier but can lead to the possibility of name clashes in large programs that use features from other libraries of code, so it should be used with care.