4.2. A first C++ program, “Hello World!”#

To get an intuition of the C++ syntax first, we will now examine a basic “Hello World” example using C++ code without going into details on how to actually run the code. Here is “Hello world!” in C++:

/* A Hello World program in C++ */
#include <iostream>

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

We will discuss three distinct parts of this basic program: comments, preprocessor commands, and the main function.

  • Any content between /* and */ is considered a comment, and therefore not processed as C++. Comments help the programmer (not the computer) understand the intent or goal of an expression, line, function or even whole C++ file. You can write anything between /* and */ anywhere in the program and this part will be disregarded by the compiler. Another way to add a comment is to place your text after //, which will be regarded as a comment until the end of the line, as you can see in the program. In contrast, comments that are started with /* can continue over multiple lines, and will only terminate once the */ is encountered.

  • Preprocessor commands start with #, and help the compiler to properly process the rest of the program. In our example, the #include <iostream> line is a preprocessor command, which tells the compiler to include a ‘header’ file. In C++, there are only few basic functions that you can use without any header files. However, if these functions are not sufficient for most programs, so additional functionality will need to be added by additional C++ libraries. These libraries contain additional functions and classes. The ‘Header’ of a library introduces these new functions and classes to the compiler, so that the compiler can recognize them. In this program, the header file iostream stands for ‘input/output stream’ library. This library contains, among other things, the cout and endl statements which are used in the main function, and let’s the program display the text Hello World! on a console. Without this header, the compiler cannot recognize the cout instruction, and will generate an error.

  • The last part of the code is main function. Each C++ program must have one and exactly one main() function. When the program starts this function will be executed, and when the main function is completed the program will finish too. Let’s take a closer look at this main function:

    • The cout instruction represents the console output, and is here used to write the string "Hello World!" to the console.

    • The endl (end line) instruction concludes the line , and makes sure an ENTER is written to the console after the string.

    • << is an operator that should be used with the cout instruction for each string, number, or other “thing” that has to be written to the console.

    • return ends the main function and finalizes the program. This program returns the value 0, which indicates to the operating system that the program terminated normally (a non-zero number could instead be used to specify an error).

    • Also notice that C++ statement ends with a ; in the main function. This tells the compiler that a command is ended. Every completed C++ instruction must end with ;, or there will be an error.

    • Additionally, see how the cout and endl functions are prefixed with std::. This tells the compiler to search for those instructions in the std namespace. Namespaces help reduce the risk of you writing a function or variable with a similar name as those in one of the libraries that you use. In this case, the iostream library, which is part of the standard C++ libraries, has defined all its functions and instructions in this std (“standard”) namespace. The text in this manual will often simply refer to the names of such functions without explicitly including their namespace. Namespaces will be discussed in more detail Section 4.3.3.

Now that the “Hello World!” program is explained, we can try to run it. However, to be able to execute the program, it has to be compiled first. Compiling can be seen as translating the programming language to a language your processor understands.

Important

In C++, every complete statement must be terminated with a semicolon ;. Here std::cout << "Hello world!" << std::endl; is one statement, and return 0; is another. Forgetting semicolons is a common source of errors for novice C++ programmers. On the other hand, a statement is allowed to span multiple lines, and multiple statements can occur on the same line.

Furthermore, a { marks the start of a block of code (for example, the content of the main() function), and } marks the end. It is good practice to indent the lines of code within the code block, but the use of white space is mostly optional in C++. Indenting just improves the readability of your code by human programmers.

In C++, all of the following are the same code:

// the good
#include <iostream>
int main() {
    std::cout << "Hello world!" << std::endl; // Print Hello World!
    return 0;
}
// the bad
#include<iostream>
int main(){std::cout<<"Hello world!"<<std::endl;/* Print Hello World! */return 0;}
// the ugly (seriously, don't make your code this unreadable)
# include<iostream>
int main (
)
{
std
::cout
  << "Hello world!"
  << std ::
endl
  ;;;; /*bunch of empty statements*/
    return
      0;
          }

4.2.1. Compiling and running C++ programs#

Every time you make a change to your code, it needs to be compiled before you can execute it. In this course manual, we will be using the “CMake” system to compile our code. While this manual could go in depth on how to compile C++ programs “by hand”, it is preferred to use “CMake” for larger and more complicated projects.

To compile a program using CMake, make a directory with your code in it. In that same directory, make a file called CMakeLists.txt. A general template for the CMakeLists.txt file is shown below:

# Declare the version of the CMake API for forward-compatibility
cmake_minimum_required(VERSION 2.8)

# Declare the name of the CMake Project project(hello_world_project)
project(hello_world_project)

# Add the directory to search for header files
include_directories(include)

# Define an executable target called hello_world_node
add_executable(hello_world hello_world.cpp)

In CMakeLists.txt, a # denotes comments, those lines will be ignored. The first line declares the minimum version of CMake that is required. We will not go in depth on this topic, but version 2.8 can be used throughout this tutorial. The second line declares the name of the project. This command is required and the naming is especially useful when combining multiple projects. The line with include_directories tells the compiler where to look for files that are called upon with #include statements. It is useful to create a directory called include/ within your project, where you store header files (more on this topic will follow later) and add it to your project with this line. The last line of CMakeLists.txt is the most important: add_executable explains that an executable needs to be built. In this case, the name of the executable will be hello_world and it is built from the file hello_world.cpp.

A C++ program can be build from multiple .cpp files, in which case you simply append them to this command, for example:

add_executable(hello_world hello_world.cpp second_file.cpp)

Before compiling, make a directory “build” in the same directory that you placed the CMakeLists.txt file. From within this “build” directory, execute the following command:

$ cmake ..

This command reads the CMakeLists.txt and generates a so-called makefile which helps you compile your program. You need to do this each time you make a change to your CMakeLists.txt. To compile the hello_world program, now run:

$ make hello_world

This compiles and generates your program hello_world. Alternatively, if you have multiple executables defined in your CMakeLists.txt, you can run the following command to compile all of them:

$ make all

Running your hello_world program is now done by calling it:

$ ./hello_world

Exercise 4.1

Compile the “Hello World!” program and run it. Change the code so it displays “Bye World!”, but don’t compile it. Run the program. What happens? Why?

4.2.2. Extending the “Hello world!” program#

It is time to add some parts to the code. For that we will declare ‘variables’. Variables are data structures that store data of a specific type. This type can be integer, character, floating point number etc. Let’s declare a variable called year with type integer:

int year;

This declaration tells the compiler to reserve some amount of memory to store an integer value. You can assign value to this variable as follows:

year = 2023;

You can also assign a value while declaring a variable:

int year = 2023;

You can print this number to console by the following way:

std::cout << year << std::endl;

You can also add some string to the text:

std::cout << "The year " << year << std::endl;

Now, let’s declare two more variables called birthyear and age also in integer type:

int birthyear = 1984; 
int age;

You can do some mathematical operations using these variables and assign the result to another variables:

age = year - birthyear;

You can now print this to the console by:

std::cout << "I am " << age << " years old" << std::endl;

Or alternatively:

std::cout << "I am " << year - birthyear << " years old" << std::endl;

So the overall program looks like:

#include <iostream>

int main() {
    int year = 2023;
    int birthyear = 1984;
    int age;

    age = year - birthyear;

    std::cout << "I am " << age << " years old" << std::endl;
    return 0;
}

You can also take input from user using cin function. This function is also a member of iostream library. This time the operator we will use is >> rather than <<. The following line requests an input from user and assigns the input to birthyear variable.

std::cin >> birthyear;

cin command stops the execution until user enters something to the console and press ENTER. Let’s modify the code in the following way:

#include <iostream>

int main() {
    int year = 2023;
    int birthyear;
    int age;

    std::cout << "Please enter your birth year:" << std::endl;
    std::cin >> birthyear;
    age = year - birthyear;

    std::cout << "You are " << age << " years old" << std::endl;
    return 0;
}

Run this program. Enter the requested input to console and observe the result.

Exercise 4.2

Write a program that takes a two numbers as side lengths of a square and prints the area of the square to the console.

Hint: you can write two cin lines, or you can use cin >> number1 >> number2;