Your First Program
Every programming tutorial starts the same way, and C++ is no exception. Let’s write, understand, and (in the next chapter) run the classic “Hello, World!” program.
hello.cpp
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}Breaking it down, line by line
#include <iostream> — a preprocessor directive that pulls in the input/output stream library, giving you access to
std::coutandstd::cin.int main() — every C++ program must have exactly one
mainfunction; it's the entry point where execution begins. Theintmeans it returns an integer.std::cout << "Hello, World!" << std::endl; — sends text to standard output.
std::coutis the output stream,<<is the "insertion operator" that feeds data into it, andstd::endlends the line.return 0; — exits
main, returning 0 to the operating system to signal the program finished successfully. A non-zero value conventionally signals an error.
The `std::` prefix and `using namespace std;`
You’ll often see cout written on its own instead of std::cout. That works because of a line at the top of the file: using namespace std;. It tells the compiler “assume anything I write might come from the std namespace,” so you can drop the prefix.
Same program, using the shortcut
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}What’s next
Writing the code is only half the story — a .cpp file isn’t a program until it’s compiled. In the next chapter, we’ll compile this exact file from the command line and see it run.
Hello, World!