Your first C++ program looks the same as every C++ program you will ever write: a set of include directives that pull in the standard library, a [[main]] function that holds the entry point, and 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 the language stops looking arbitrary.
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
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}Save that as hello.cpp and you have a legal, complete, compilable C++ program. There is no header file to declare, no project file, 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 compiling.
#include <iostream>brings in the standard stream classes, which is wherestd::coutandstd::endlare declared. - The function signature
int main()names the function that the operating system calls first. Its return type isint, 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
mainand disappears whenmainreturns. - 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, which lets you write cout directly. It is convenient in small programs and 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, forcing 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 interleaved with something else.
#include
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 — two characters in the source that mean one newline in the output. 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 since C++ guarantees that reaching the end of main returns zero, but writing it explicitly is 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. Write return 1; at the end of a program that could not do its job and any script that calls it can react.
#include
#include
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 exits cleanly:
Converting from CelsiusRunning that program with an unexpected unit writes the complaint to standard error and exits with status one. That distinction between std::cout and std::cerr — normal output versus diagnostics — is a habit worth forming on day one, because 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* something is the way it is, not to narrate what the code obviously does. A comment that repeats the next line is noise; a comment that explains a non-obvious choice 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, #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, which is exactly what you want for a header sitting next to the source that includes it.
Quick reference
- A complete C++ program is headers plus a
mainfunction; nothing else is required. #include <iostream>is what gives youstd::cout.std::coutwrites to standard output;std::cerrwrites diagnostics to standard error.- Every statement ends with a semicolon; every function body is wrapped in braces.
return 0;signals success to the shell and 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;]] to confirm the compiler is happy without it.