Hello World in C++

Prints "Hello World" in C++ with cout. Covers #include, main, and return 0.

BeginnerBasic ProgramsExample 1 of 14
hello-world.cpp
1// This line allows us to use input and output (like printing on the screen)
2#include <iostream>
3using namespace std;
4
5// main() function: this is where every C++ program starts running
6int main() {
7 // This line prints "Hello World" on the screen
8 cout << "Hello World";
9
10 // This line tells the computer that the program ended successfully
11 return 0;
12}

Output

Hello World

What's going on

A C++ Hello World program prints text with cout. Four statements. That's the whole file.

#include <iostream>

Skip this and cout is an unknown name. The compiler dies. iostream is the header that knows how to print (and later, how to read with cin).

using namespace std;

cout lives in std. This line lets you write cout instead of std::cout. Fine in a short file. Bigger projects often skip it and type std:: so names don't collide.

int main() {

Execution starts here. No main, no program. int means it returns a number to the OS. The { } wrap the body.

cout << "Hello World";

The only line that does work. << sends the string to the screen. Drop the quotes and C++ looks for a variable called Hello. Drop the semicolon and the error points at the *next* line, which is annoying.

return 0;

Zero means the process succeeded. You can omit this in modern C++; main still returns 0. Writing it keeps the success code obvious.

Change the string, rebuild, and the output should change. If it does, the toolchain works. Next is a string variable — Display Your Name — then cin for real input.