Now that we know what C++ is, it's time to write our first C++ program. We will write it, compile it, run it, and then go through it line by line until every symbol makes sense. We will also deliberately break it to see what compiler errors look like, because reading errors is a skill every programmer needs.
The Program
Here is the classic first program in C++:
#include <iostream>
int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}
Output:
Hello World!
Only six lines, but each one has a job. Let's understand them one by one.
Line 1: #include <iostream>
#include <iostream>
Lines that start with # are preprocessor directives. They are handled before the real compilation starts.
#includetells the preprocessor to copy the contents of another file (a header) into your program at that point.
The header <iostream> ("input-output stream") declares std::cout for output and std::cin for input. Without it, the compiler has no idea what std::cout is.
Notice that C++ standard headers have no .h at the end. In C you wrote <stdio.h>; in C++ the standard header is just <iostream>. (The C headers are also available in C++ with a c in front and no .h, such as <cmath> and <cstdio>.)
Line 3: int main()
int main() {
This defines a function named main.
Every C++ program must have exactly one function named
main. When you run the program, execution starts at the beginning ofmain.
intis the return type:maingives an integer back to the operating system when it finishes. In standard C++, the return type ofmainmust beint. Writingvoid main()is not valid C++, even though some old compilers (such as Turbo C++) accepted it.The empty parentheses
()meanmaintakes no arguments here. (Another allowed form receives command-line arguments; we will see it in the next chapter.)The curly braces
{ }mark the body of the function. Everything between them belongs tomain.
Line 4: std::cout << "Hello World!" << std::endl;
This is the line that actually prints. Let's split it into parts:
| Part | Meaning |
|---|---|
std | The standard namespace. Everything from the C++ standard library lives inside a "family name" called std. |
:: | The scope resolution operator. std::cout means "the cout that belongs to std". |
cout | "character output": an object connected to the standard output, normally your screen. |
<< | The insertion operator. It sends the value on its right into the stream on its left. |
"Hello World!" | A string literal: text written directly in the code, inside double quotes. |
std::endl | Writes a newline character and flushes the output (forces it to appear immediately). |
; | Ends the statement. |
A nice way to picture << is as an arrow showing the direction in which data flows:
"Hello World!" ──► std::cout ──► screen
Why does << work several times in one statement? Each std::cout << something gives back std::cout itself, so the next << also writes into std::cout:
std::cout << "Hello World!" << std::endl;
└──────────┬──────────────┘
gives back std::cout, then std::cout << std::endl
This is called chaining. You will learn how it works internally in the chapter Operator Overloading.
Line 5: return 0;
return 0; ends main and sends the value 0 to the operating system. By convention:
0means "the program finished successfully".A non-zero value means "something went wrong". Scripts and build tools use this value to decide whether a step failed.
One special rule: main is the only function where you may leave out the return statement. If control reaches the closing brace of main, it behaves as if you wrote return 0;. Many programs in this tutorial use this rule. For any other function with a non-void return type, falling off the end without returning a value is undefined behavior.
Compiling and Running the Program
C++ source code cannot run directly. It must first be compiled into an executable. Save the program in a file named hello.cpp (common extensions are .cpp, .cc and .cxx) and run:
g++ -std=c++23 -Wall -Wextra hello.cpp -o hello
./hello
| Part | Meaning |
|---|---|
g++ | The GCC C++ compiler (use clang++ for Clang) |
-std=c++23 | Compile using the C++23 standard |
-Wall -Wextra | Turn on most useful warnings. Always use them; warnings catch real bugs. |
hello.cpp | The source file to compile |
-o hello | Name the output executable hello (without -o, GCC names it a.out on Linux/macOS and a.exe on Windows) |
./hello | Run the executable from the current folder (on Windows Command Prompt or PowerShell, run hello.exe or .\hello) |
If there are no errors, the compiler prints nothing and creates the executable. Silence means success.
Where can I get a compiler?
Linux: install GCC with your package manager (for example
sudo apt install g++on Ubuntu).Windows: install MSYS2 and its MinGW-w64 GCC package, use WSL (Windows Subsystem for Linux), or install Visual Studio with the "Desktop development with C++" workload.
macOS: run
xcode-select --installto get Clang.No installation: online compilers such as Compiler Explorer (godbolt.org) let you compile and run code in the browser.
An IDE such as Visual Studio, VS Code (with the C/C++ extension), CLion or Code::Blocks runs these same compile and run steps when you press the Run button.
Printing More Than One Line
#include <iostream>
int main() {
std::cout << "Hello!\n";
std::cout << "I am learning C++.\n";
std::cout << "C++ is fast" << " and " << "powerful." << '\n';
return 0;
}
Output:
Hello!
I am learning C++.
C++ is fast and powerful.
Here we used '\n' instead of std::endl. '\n' is the newline character. It can be written as a character ('\n') or inside a string ("Hello!\n").
Output only moves to the next line when you print a newline. std::cout never adds one automatically:
#include <iostream>
int main() {
std::cout << "Hello ";
std::cout << "World";
std::cout << '\n';
std::cout << "Line 1\nLine 2\n";
}
Output:
Hello World
Line 1
Line 2
std::endl vs '\n'
'\n' | std::endl |
|---|---|
| Only writes a newline character | Writes a newline and flushes the stream |
| Fast | Slower when used many times, because every flush is a request to the operating system |
| Preferred in most code | Useful when output must appear immediately (for example, before a program might crash) |
To flush means to take the characters waiting in the output buffer (a temporary storage area in memory) and actually hand them to the screen or file. In a loop that prints a million lines, using std::endl can make the program noticeably slower, which is why competitive programmers always use '\n'.
Printing Numbers and Expressions
std::cout knows how to print numbers too, and it prints the result of an expression:
#include <iostream>
int main() {
std::cout << 100 << '\n';
std::cout << 3.14 << '\n';
std::cout << "10 + 20 = " << 10 + 20 << '\n';
std::cout << "7 / 2 = " << 7 / 2 << '\n';
std::cout << "7.0 / 2 = " << 7.0 / 2 << '\n';
return 0;
}
Output:
100
3.14
10 + 20 = 30
7 / 2 = 3
7.0 / 2 = 3.5
Look closely at 7 / 2: it printed 3, not 3.5. When both operands are integers, C++ does integer division and throws away the fractional part. With 7.0 / 2, one operand is a floating-point number, so the result is 3.5. We will study this properly in the chapters Operators and Type Conversion & Casting.
The Modern Way: std::println (C++23)
C++23 added the header <print> with std::print and std::println. std::println prints and then adds a newline. The {} markers are replaced by the values that follow, in order:
#include <print>
int main() {
std::println("Hello World!");
std::println("{} + {} = {}", 10, 20, 10 + 20);
}
Output:
Hello World!
10 + 20 = 30
This needs a C++23 compiler and library (GCC 14 or newer, or a recent Clang or MSVC). Because std::cout works everywhere and is still used in most code, books and exams, this tutorial mainly uses std::cout. The chapter Input & Output covers both in detail.
When Things Go Wrong: Compiler Errors
Every programmer sees compiler errors every day. The trick is to read them calmly. Let's break our program on purpose.
Error 1: a missing semicolon
#include <iostream>
int main() {
std::cout << "Hello World!" << '\n'
return 0;
}
Compiler output:
hello.cpp: In function ‘int main()’:
hello.cpp:4:40: error: expected ‘;’ before ‘return’
4 | std::cout << "Hello World!" << '\n'
| ^
| ;
5 | return 0;
| ~~~~~~
The format is file:line:column: error: message. The compiler noticed the problem when it reached return on line 5, but it points at the end of line 4, where the ; should be, and even suggests the fix. A common beginner confusion: the reported line is often the line just after the real mistake.
Error 2: forgetting std::
#include <iostream>
int main() {
cout << "Hello\n";
}
hello.cpp: In function ‘int main()’:
hello.cpp:4:5: error: ‘cout’ was not declared in this scope; did you mean ‘std::cout’?
4 | cout << "Hello\n";
| ^~~~
| std::cout
In file included from hello.cpp:1:
/usr/include/c++/15/iostream:65:18: note: ‘std::cout’ declared here
65 | extern ostream cout; ///< Linked to standard output
| ^~~~
cout lives inside the namespace std, so the bare name cout is unknown. Write std::cout. (The next chapter explains using declarations, which let you skip the std:: prefix.)
Error 3: forgetting the #include
int main() {
std::cout << "Hello\n";
}
hello.cpp: In function ‘int main()’:
hello.cpp:2:10: error: ‘cout’ is not a member of ‘std’
2 | std::cout << "Hello\n";
| ^~~~
hello.cpp:1:1: note: ‘std::cout’ is defined in header ‘<iostream>’; this is probably fixable by adding ‘#include <iostream>’
+++ |+#include <iostream>
1 | int main() {
Modern compilers are helpful: GCC even tells you which header to include.
When you get many errors at once, fix the first one and compile again. One mistake often causes a chain of confusing errors after it.
Errors vs warnings
| Error | Warning |
|---|---|
| The code is not valid C++ | The code is valid but looks suspicious |
| No executable is produced | The executable is still produced |
| Example: missing semicolon | Example: using a variable before giving it a value |
Treat warnings seriously. Many real bugs show up first as warnings. You can even make the compiler treat every warning as an error with -Werror.
Common Mistakes
Writing
void main(). Standard C++ requiresint main().Using
#include <iostream.h>. That was a pre-standard header from the 1990s (for example in Turbo C++). It does not exist in modern compilers.Mixing up
<<and>>. Output usesstd::cout <<; input usesstd::cin >>. Think of the arrows as showing where the data goes.Using single quotes for text.
'Hello'is wrong; single quotes are for one character, like'A'. Text needs double quotes:"Hello".Forgetting the newline, so all the output ends up on one line.
Wrong capital letters. C++ is case-sensitive:
Main,COUTandStd::coutare all different (and wrong) names.Running an old executable. If you edit the code but forget to recompile, you are still running the old program.
Interview / Exam Questions
Can a C++ program run without a main() function?
A normal (hosted) C++ program must define main; otherwise the linker reports an "undefined reference to main" error. Code that runs before main is possible (for example, constructors of global objects), but main is still the official entry point. Only freestanding environments, such as some embedded systems, define their own startup.
Is void main() valid in C++?
No. The C++ standard requires main to return int. GCC rejects void main() with the error "'::main' must return 'int'".
What happens if main has no return statement?
It is fine. Reaching the end of main is the same as return 0;. This special rule applies only to main.
What is the difference between std::endl and '\n'?
Both end the line, but std::endl also flushes the output buffer. Flushing repeatedly is slow, so '\n' is preferred unless you specifically need the output to appear immediately.
What does :: mean in std::cout?
:: is the scope resolution operator. std::cout means the name cout declared inside the namespace std.
What is printed by std::cout << 9 / 2 << " " << 9 % 2;?
4 1. Integer division drops the fractional part, and % gives the remainder.
Try It Yourself
Write a program that prints your name, your college and your favourite programming language on three separate lines. Then print the result of 365 * 24 with a label, like Hours in a year: 8760. Experiment: remove a semicolon or misspell cout, and read the error the compiler gives you.
In Simple Words
A C++ program starts in
int main(). We include<iostream>to usestd::cout, send values to it with<<, end lines with'\n', and compile withg++before running.
#include <iostream> → brings in std::cout
int main() { ... } → execution starts here
std::cout << x; → print x
'\n' → newline (std::endl = newline + flush)
return 0; → success (optional at the end of main)
g++ -std=c++23 -Wall -Wextra hello.cpp -o hello → compile
./hello → run
In the next chapter, C++ Program Structure, we will look at the full layout of a C++ program and what really happens during compilation and linking.