Chapter 2: Hello, C++!

This chapter gives you a sample of C++ so that you can ease into both your initial development environment, and into your new programming language. We’re going to write two very simple C++ programs and take a look at what Compiler Explorer gives us.

Chapter table of contents

  1. Chapter 2: Hello, C++!
    1. Objectives and outcomes
    2. Acknowledgements
    3. C++ is a compiled language
    4. Hello, Compiler Explorer!
    5. The simplest C++ program
    6. Classic hello world
      1. Greeting with a date
    7. Feedback
    8. Summary

Objectives and outcomes

Objective (you will develop) Outcome (you will be able to)
an appreciation for Compiler Explorer
  • describe what you can achieve using Compiler Explorer
skills in writing simple C++ programs
  • synthesise a C++ program that writes to standard output
  • describe the contents of a function

Acknowledgements

Thank you to Sy Brand and Hana Dusíková for providing feedback on early drafts of this blog.

C++ is a compiled language

Computers are only interested in machine code that instructs their circuitry to do the next thing (for some definition of “thing”). We don’t directly understand electricity, so we need some way to communicate with both the computer and other human programmers. This is where code comes in: it’s a medium that humans can be trained to understand, and can be translated to electricity by a computer. There are two main methods of translation: interpretation and compilation.

Interpreters are programs that translate code and execute it at the same time, but the catch is that you always need to have the code and the interpreter on-hand. Python and JavaScript are traditionally interpreted languages.

Compilers are programs that translate code and output a file for later use. If the file is executable, you can run the program without the need for the code or the compiler, but it comes with the trade-off of only being able to run the program on certain computers (e.g. a program that was compiled for Linux cannot run on macOS). C++ and Rust fall into this category, and are known as compiled languages.

Hello, Compiler Explorer!

Let’s start by opening up our editor, Compiler Explorer. Compiler Explorer is an online tool that many developers use to prototype simple content and see how different compilers process their code. In our case, we’re going to be using it as an off-the-shelf editor that will work on pretty much any computer that isn’t a phone.

A screenshot showing our Compiler Explorer environment.

You should see an empty textbox that takes up about half the screen on the left-hand side of the page, and message in the pane to the right.

Could not execute the program
Compiler returned: -1
Compiler stderr

<File example.cpp has no content or file is missing>

Our primary usage of Compiler Explorer in Module 1 will be to write code into the textbox and read the output that the compiler provides.

Compiler Explorer automatically updates as you type, so we don’t need to save any files. This might mean that you’ll often be told that programs are incorrect until you finish typing. You can hide the output until you’ve finished typing by pressing the ‘Compiler output’ button in the right pane.

In this case, the reason is because we haven’t written any code. Let’s fix that. ## The simplest C++ program

To make the message from the previous section go away, we’ll write the simplest possible C++ program into the textbox on the left.

int main() {}

After a few seconds, you should notice that the output changes to

Program returned: 0

If you see that output, it means that we were able to successfully run our program. Congratulations! We’ve just written our first C++ program! But what did we do?

This program consists of a global nullary function called main1. The program does nothing.

In C++, programs need what’s known as an entry point: that is, a way that the system can interface with our program to start execution. This entry point is always called main, and it always needs to have the return type2 int. Since the entry point is always known as main, and it’s always required, our tools assume that we’re going to provide it in some fashion.

Like most modern programming languages, C++ uses parentheses (( and )) to group function parameters. In this case, there aren’t any parameters, so we leave the parentheses empty. We use braces ({ and }) to group various other things. Since we don’t have anything to do yet, we leave the braces empty too. C++ is case-sensitive, so if, for example, we change main to Main, then our tools won’t be able to find the entry point any more, and will complain once again.

Classic hello world

Our current program doesn’t do anything useful. A classic hello world program is slightly more interesting than this. Let’s get the following source into Compiler Explorer.

// This is my first meaningful C++ program!
#include <fmt/format.h>

int main()
{
  fmt::print("Hello, world!\n");
}

After a few seconds, you should see the pane on the right now show

Program returned: 0
Program stdout

Hello, world!

The first line starts with //. Two consecutive forward slashes start a comment, which is delimited by the line’s end.

Source files in C++ are bare-bones: that means that most functionality needs to be imported from some library. In this program, we’re writing to standard output, so we need to include an I/O library that gives us the facilities to do that. To import our library, we placed #include <fmt/format.h> at the top of the file. This lets us use the fmt::print function below. If we remove this line, then this appears:

Could not execute the program
Compiler returned: 1
Compiler stderr

<source>:4:3: error: use of undeclared identifier 'fmt'
  fmt::print("Hello, world!\n");
  ^
1 error generated.

The "Hello, world!\n" enclosed in double quotes (") is a string literal, where the \n is processed as a line-feed character. In C++, all string literals are enclosed in double quotes, unlike some languages like Python, where you can interchange single quotes (') and double quotes.

fmt::print("Hello, world!\n") is a function call, where our "Hello, world!\n" string literal is passed as a function argument. This call to fmt::print writes the string literal to standard output.

Most statements in C++ end with a semicolon (;). Ending statements with semicolons lets us split them over multiple lines, when they become too long.

Greeting with a date

fmt::print does special processing that replaces {} in string literals with external values. The first {} is replaced by the second argument to fmt::print, the second {} is replaced by the third argument, and so on. Let’s use this to print out the date.

int main()
{
  fmt::print("Hello, world!\n");
  fmt::print("It is {}-{}-{}.\n", 2022, 12, 30);
}
Hello, world!
It is 2022-12-30.

Feedback

If you’d like to provide feedback regarding this series, please file an issue on GitHub.

If you’re interested in reading future chapters, subscribe to my RSS feed to receive a notification at the time of publication. If you’d previously subscribed to my feed on my old website (www.cjdb.com.au), please be sure to note the new domain!

Summary

And that’s a wrap for our first two C++ programs! In this chapter, we learnt:

  • about Compiler Explorer, our editor
  • that main is a function required for all C++ programs
  • how to import a library
  • how to write to standard output

  1. A “nullary function” is one that takes zero arguments.↩︎

  2. If you’re not familiar with “return types”, we’ll cover what that means in Chapter 4. For now, assume it means that int always needs to precede main.↩︎