Your first C++ program looks the same as every C++ program that you will ever write. There are include directives that pull in the standard library, there is a main function that holds the entry point, and there are statements inside it that do the actual work. The famous hello world is four meaningful lines surrounded by punctuation, and once you know what each part does then the language stops looking arbitrary.
The previous lesson in this module covered "How Do You Install a C++ Compiler on Windows, Linux and macOS?", and the next lesson in this module is about "How Do You Compile and Run C++ From the Command Line?".
The shortest complete C++ program
Here is the whole thing. It is called "hello world" for historical reasons, and it is still the correct first program to write, because every piece of it appears in real code.
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}Save that as hello.cpp and you have a legal, complete and compilable C++ program. There is no header file to declare, there is no project file, and there is no package to configure. One file, one compiler invocation, one program.
Hello, world!What each part of your first C++ program does
Line by line, that program contains four ideas.
-
The include directive tells the preprocessor to paste another file's contents in before the compilation happens. The line
#include <iostream>brings in the standard stream classes, and that is wherestd::coutandstd::endlare declared. -
The function signature
int main()names the function that the operating system calls first. Its return type is int, so the program hands an integer status back to the shell. - The curly braces open and close the function body. Everything inside those braces belongs to main, and it disappears when main returns.
- The statement inside the body does the visible work. In C++ a statement ends with a semicolon.
The double colon in std::cout is a scope resolution operator. It says "the cout object that lives in namespace std". Every name in the C++ standard library lives in that namespace, which is why you almost always see the prefix. A popular alternative is a using namespace std; directive near the top of the file, and that lets you write cout directly. It is convenient in small programs and it is discouraged in headers, because it sprays unqualified names into every file that includes yours.
Why the first program uses std::endl at all
std::endl does two things. It writes a newline character, and it flushes the stream, which forces the buffered text out to the terminal immediately. For a first program that is a useful demonstration, because you want to see the output before the program ends.
For anything else, a plain "\n" is better. Flushing on every line costs real time, and you do not need it unless you are debugging output that is mixed in with something else.
#include <iostream>
int main() {
std::cout << "Temperature: 21.5 C\n";
std::cout << "Feels like 20.9 C\n";
return 0;
}The console shows exactly what the two \n characters asked for.
Temperature: 21.5 C
Feels like 20.9 CThe \n inside the string literal is an escape sequence. It is two characters in the source that mean one newline in the output. The other common escapes are \t for a tab, \" for a double quote and \\ for a literal backslash.
Return 0 and the exit status
The final return 0; is technically optional, because C++ guarantees that reaching the end of main returns zero. Writing it out is still good practice, because it makes the intent obvious to the next reader.
The value matters. Zero conventionally means success, and anything else means failure, and the shell uses it. You write return 1; at the end of a program that could not do its job, and then any script that calls it can react.
#include <iostream>
#include <string>
int main() {
std::string units = "Celsius";
if (units != "Celsius" && units != "Fahrenheit") {
std::cerr << "Unsupported unit: " << units << '\n';
return 1;
}
std::cout << "Converting from " << units << '\n';
return 0;
}With the supported unit the program prints a single line and it exits cleanly.
Converting from CelsiusRunning that program with an unexpected unit writes the complaint to standard error, and it exits with status one. That distinction between std::cout and std::cerr is normal output against diagnostics, and it is a habit worth forming on day one. It is what lets you pipe real results out of a program while keeping error messages out of the data.
Comments and code that reads well
Comments do not change how the program runs. C++ offers three styles, and they serve different purposes.
// A single-line comment, for a short note next to one line of code.
/*
A block comment. It can span
several lines, which makes it the right
choice for a longer explanation.
*/
/**
A doc comment. Tooling reads these to build
documentation, and they conventionally describe
what a function does rather than how it works.
*/
int main() {
// Comments can sit inside a function body too.
return 0;
}Use comments to explain why the code is the way it is, and not to narrate what the code obviously does. A comment that repeats the next line is noise. A comment that explains a choice that is not obvious saves the next reader an afternoon.
The rules every C++ program follows
Across every program in this tutorial, four rules hold without exception.
- Every statement ends with a semicolon.
- Identifiers are case-sensitive, so
coutandCoutare different names. - Blocks are delimited by braces, and braces scope names.
mainis the entry point, and the operating system calls it.
On top of that, the #include directives come before anything else in the file, and the standard headers are included by angle brackets while your own headers are included by quotes. The angle bracket form searches the compiler's system include path. The quoted form searches the directory of the current file first, and that is exactly what you want for a header that sits next to the source that includes it.
Quick reference
- A complete C++ program is headers plus a main function, and nothing else is required.
#include <iostream>is what gives youstd::cout.std::coutwrites to standard output, andstd::cerrwrites diagnostics to standard error.- Every statement ends with a semicolon, and every function body is wrapped in braces.
return 0;signals success to the shell, and it is what a script checks.- Prefer
"\n"overstd::endlonce you move past your first program.
Try it yourself: type the hello world program from memory in an empty file and compile it. Then change it into a temperature converter that prints a converted value, swap std::endl for "\n", and remove the return 0; so that you can confirm the compiler is happy without it.