BeginnerLesson 1 of 18
Hello World, main and #include – C++
Structure of a C++ program, output with std::cout and the path from source code to program.
Every C++ program starts in the function main. With #include you include headers of the standard library, and std::cout writes to the console. std:: is the namespace of the standard library.
#include <iostream>
int main() {
std::cout << "Hello World!" << std::endl;
return 0; // optional: otherwise main returns 0 automatically
}The << operator "pushes" values into the output stream and can be chained. You write comments with // or /* ... */. For a line break, use \n – std::endl also flushes the buffer and is therefore slower.
#include <iostream>
int main() {
// Single-line comment
/* Multi-line
comment */
std::cout << "I'm learning " << "C++" << '\n';
std::cout << "Number: " << 42 << ", Pi: " << 3.14 << '\n';
std::cout << "Line 1\nLine 2\n";
}The path to the finished program consists of three steps: the preprocessor inserts the headers, the compiler translates every .cpp file into machine code (object file), and the linker joins everything into an executable file.
TipPrefer writing out
std:: over using using namespace std;. In headers, using namespace is forbidden because it burdens all users of the header with name collisions. Since C++20, there is also std::format for formatted output (GCC 13+/Clang 17+).WarningA missing semicolon or a forgotten
#include often leads to long error messages. Always read the first error message first – the later ones are usually follow-up errors.