The first C++ program

When you start learning a programming language, your first task is to make sure you understand how to use the system and run your first program. The more trivial the program the better, because if a problem occurs there is no chance the problem is in the program itself: the problem must be in the system that runs the program, such as how it has been set up.

This page is here for historical interestL if you have been following the pages up to here everything stated here should be familiar and should be useful revision.

Everyone's first program does the following. It simply prints the message "Hello, world!" and halts.

As simple as this is, writing and running such as program tests a number of important things. It tests that your system is working OK, it tests that you can use the editor correctly and save your file in the right location, it tests that the compiler works, and it tests that you can successfully run the resulting program. So here is the program in C++, with the traditional message left unchanged.

// helloworld.cpp (click here to download)

/* 
  Everyone's first program: prints a message to the screen
  Richard Kaye January 2017 for 2NP
 */

#include <iostream>

using namespace std;

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

I need to explain the main features of this program and what the various lines do.

Exercise.

Type this program into an editor or IDE, compile and run it. Now change the message and re-run it and check the result is as you expect. See the web page on using Dev-C++.

Traps for beginners.

There are a number of potential traps for beginners here, mostly due to the fact that the syntax is precise and unforgiving. Pay attention to details! The reason that syntax is unforgiving is to ensure that the compiler cannot possibly misunderstand you and "guess" the wrong thing. In other words precise syntax will help you in the long run, but you must learn to be precise too!

For historical reasons things starting with # are not statements so #include <iostream> doesn't get a semicolon. The rules for when a semicolon is needed after } or ) are more complicated, and you will learn these as you need them. (Note: a semicolon is not needed after the body of a function you are giving, and a semicolon must not be placed between main() and the corresponding { that follows.)

Indentation of code is a useful quick visual way of showing what sections require what kinds of brackets to complete them and is strongly recommended. But note that the compiler does not itself pay any attention to the indentation and just because your code is indented does not mean the compiler will understand it in the way you intend.