C++ Hello World Program
The Hello World program is the traditional first program in almost every language, and C++ is no exception. It does only one thing: it prints a short message on the screen. That sounds trivial, but getting it to run proves that your compiler is installed, that you can save, build and execute a source file, and that you understand the minimum structure every C++ program needs.
This tutorial walks through the program line by line, shows how to compile and run it, and then covers the small variations and mistakes that beginners meet in their first hour with the language.
What a C++ Program Is Made Of
A C++ source file is plain text, usually saved with the extension .cpp. The computer cannot run that text directly. A program called a compiler translates it into machine code, and a linker joins that machine code with the library code it depends on to produce an executable file.
Even the smallest useful program has three parts:
- A header inclusion that brings in the declarations for the library features you want to use.
- A
mainfunction, which is where execution always begins. - One or more statements inside
mainthat do the actual work.
Everything else you will learn in C++ (variables, loops, classes, templates) is built on top of this skeleton.
The Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Output
Hello, World!
Line-by-Line Explanation
#include
Lines that start with # are preprocessor directives. The preprocessor runs before the compiler proper and handles simple text-level instructions. #include <iostream> tells it to insert the contents of the standard header iostream at that point.
iostream stands for input/output stream. It declares cout for output and cin for input, among other things. Without this line the compiler has never heard of cout and reports an error.
using namespace std;
The standard library places its names inside a namespace called std. A namespace is a named scope that prevents name clashes between different libraries. The full name of cout is therefore std::cout.
The line using namespace std; tells the compiler to look in std automatically, so you can write cout instead of std::cout. It is convenient in small programs. In larger projects many developers avoid it, because it pulls every standard name into your code and can cause conflicts with your own names.
int main()
main is the entry point of the program. When the operating system starts your executable, control is handed to main. A program must have exactly one function with this name.
The word int before it is the return type. It says that main gives back an integer to the operating system when it finishes. The empty parentheses mean this version of main takes no arguments.
The braces
The curly braces { and } mark the body of the function. Every statement between them belongs to main. Forgetting the closing brace is one of the most common beginner errors.
cout << "Hello, World!";
This is the statement that does the visible work. cout (pronounced "see-out") is the standard output stream, normally connected to the console. The << symbol is the stream insertion operator; it sends the value on its right into the stream on its left.
The text between double quotes is a string literal, a fixed sequence of characters. The statement ends with a semicolon, as every C++ statement does.
return 0;
This ends main and hands the value 0 back to the operating system. By convention 0 means "the program finished successfully" and any other value signals a problem. Scripts and build tools read this value to decide whether a program worked.
main is special: if you leave out return 0;, C++ behaves as if it were there. Writing it explicitly is still a good habit while you are learning.Compiling and Running
How you build the program depends on your tools. With the GNU compiler, save the code as hello.cpp, open a terminal in the same folder and run:
g++ hello.cpp -o hello
./hello
The first command compiles hello.cpp and writes an executable named hello. The second command runs it. On Windows the executable is called hello.exe and you run it by typing hello or .\hello.
If you use an IDE such as Visual Studio or Code::Blocks, the Build and Run buttons perform the same two steps for you.
Adding a New Line
The basic program prints the message and leaves the cursor on the same line. That is why your terminal prompt may appear right after the exclamation mark. To end the line, send a newline to the stream.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
cout << "Welcome to C++\n";
return 0;
}
Hello, World!
Welcome to C++
There are two ways to end a line. endl writes a newline character and also flushes the stream, which means it forces any buffered text to be written out immediately. The escape sequence \n writes only the newline. Both give the same visible result here. In programs that print a great deal, \n is faster because it avoids repeated flushing.
Notice that << can be chained. Each << returns the stream, so several values can be sent in one statement.
Writing It Without using namespace std
Many style guides prefer the explicit prefix. The program is the same apart from the std:: in front of each standard name.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Hello, World!
Comments
A comment is text the compiler ignores. Comments explain the code to human readers. C++ has two forms.
#include <iostream>
using namespace std;
int main() {
// This is a single-line comment
/* This comment can
span several lines */
cout << "Comments do not appear in the output" << endl;
return 0;
}
Comments do not appear in the output
Common Mistakes
Most first-day errors fall into a short list. The compiler's messages can look intimidating, so it helps to know what usually causes them.
| Mistake | What happens |
|---|---|
| Missing semicolon after a statement | Compile error, usually reported on the following line |
Writing Cout or COUT | Compile error, because C++ is case-sensitive |
Forgetting #include <iostream> | Compile error saying cout is not declared |
Leaving out using namespace std; and also std:: | Compile error saying cout is not declared in this scope |
Using >> instead of << with cout | Compile error, since >> is the input operator |
| Single quotes around the message | Warning or error, because single quotes are for one character only |
Naming the function Main | Linker error, because no main function can be found |
| Unmatched braces | Compile error at the end of the file |
When you get an error, read the first message and fix that one before looking at the others. A single missing semicolon can produce several follow-on messages that disappear once the real problem is fixed.
Good Habits to Start With
- Indent the statements inside
mainconsistently. The compiler does not care, but readers do. - Save the file before compiling, and give it a meaningful name that ends in
.cpp. - Compile often. Finding one error in two new lines is much easier than finding five errors in fifty.
- Type the program yourself instead of pasting it. Typing builds a feel for the punctuation.
Extending the Program
Once the basic version runs, a natural next step is to read input. cin with the extraction operator >> reads a value typed by the user.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " << name << "!" << endl;
return 0;
}
Enter your name: Asha
Hello, Asha!
Here string is a type from the <string> header that holds text. cin >> name reads one word, stopping at the first space.
Practice Exercises
- Change the program so that it prints your own name and city on two separate lines.
- Print the same message three times using three
coutstatements, then do it again with one statement and chained<<operators. - Remove the semicolon after the
coutline, compile, and read the error message. Put it back and confirm the program builds again. - Rewrite the program without
using namespace std;. - Change
return 0;toreturn 1;and find out how your terminal or IDE reports the exit code.
Summary
A Hello World program contains a header inclusion, a main function and at least one statement. #include <iostream> makes cout available, main is where execution starts, cout << writes text to the console, and return 0; reports success to the operating system. The source file must be compiled into an executable before it can run. With this skeleton working, you have a place to try every other C++ feature you learn next.