Skip to content

Hello World — Your First C++ Program Explained Line by Line

DodaTech Updated 2026-06-28 7 min read

In this tutorial, you will learn about Hello World. We cover key concepts, practical examples, and best practices to help you master this topic.

The classic Hello World program in C++ reveals how the language handles input-output, namespaces, function definitions, and the compilation pipeline in just a few lines of code.

What You'll Learn

You will dissect every line of a minimal C++ program, understand what #include <iostream> does and why it is needed, learn the role of the main function and its return value, use std::cout for output and std::cin for input, and compile your program with verbose output to see each compilation stage.

Why It Matters

Hello World is the first step in every language because it validates your entire toolchain. But in C++, Hello World is also a microcosm of the language's philosophy: you see the preprocessor (include), the namespace system (std::), function overloading (operator<<), and object lifetimes (stream objects). Understanding this tiny program deeply pays dividends.

Learning Path

graph LR
    A["02: Installing a Compiler"] --> B["03: Hello World"]
    B --> C["04: Variables & Types"]
    C --> D["05: Constants & Modifiers"]
    style A fill:#4a90d9,stroke:#2c5f8a,color:#fff
    style B fill:#4a90d9,stroke:#2c5f8a,color:#fff
    style C fill:#4a90d9,stroke:#2c5f8a,color:#fff
    style D fill:#4a90d9,stroke:#2c5f8a,color:#fff

The Program

#include <iostream>

int main() {
    std::cout << "Hello, World!\n";
    return 0;
}

Save this as hello.cpp, then compile and run:

g++ -std=c++17 -Wall hello.cpp -o hello
./hello

Expected output:

Hello, World!

Line-by-Line Breakdown

Line 1: #include <iostream>

This is a preprocessor directive. The preprocessor runs before the compiler and performs text substitution. #include <iostream> tells the preprocessor to find the file iostream in the system's include path and paste its entire contents into this source file.

What is iostream? It is a header file that declares input-output stream objects: std::cin (standard input), std::cout (standard output), std::cerr (standard error, unbuffered), and std::clog (standard error, buffered). Without this include, the compiler would not know what std::cout means.

Line 2: Empty Line

Whitespace is ignored by the compiler. Use blank lines to separate logical sections of your code for human readability.

Line 3: int main() {

Every C++ program must have a main function. It is the entry point: when the operating system loads your program, it calls main. The int before main indicates that the function returns an integer value to the operating system. The parentheses () mean this function takes no arguments (though main can also take command-line arguments: int main(int argc, char* argv[])).

The opening brace { begins the function body.

Line 4: std::cout << "Hello, World!\n";

This is the only statement that does actual work. Let us break it into parts:

  • std:: is a namespace qualifier. The name cout lives inside the std (standard) namespace. Namespaces prevent name collisions. Without std::, the compiler looks for cout in the global namespace, which does not contain it.

  • cout stands for "character output." It is a global object (an instance of std::ostream) connected to standard output, typically your terminal.

  • << is the stream insertion operator. It looks like bitshift (and indeed it is the same operator, overloaded). It takes data from the right side and inserts it into the stream on the left side. The expression returns the stream itself, enabling chaining.

  • "Hello, World!\n" is a string literal: a sequence of characters enclosed in double quotes. The \n is an escape sequence representing a newline character (ASCII 10).

The semicolon ; terminates the statement. Every expression statement in C++ ends with a semicolon. Forgetting it is one of the most common compilation errors.

Line 5: return 0;

The return statement exits the main function and sends a value back to the operating system. A return value of 0 (or EXIT_SUCCESS from <cstdlib>) signals successful execution. Non-zero values indicate errors. The main function is unique: if you omit the return 0; statement, the compiler automatically inserts it (in C++ only, not in C).

Line 6: }

The closing brace ends the function body.

Compilation Stages in Practice

Compile your program with verbose output to see each stage:

g++ -std=c++17 -Wall -v hello.cpp -o hello

The -v flag shows the commands executed at each stage. You will see:

  1. The preprocessor running (cc1plus with -E)
  2. The compiler generating assembly (hello.s)
  3. The assembler creating the object file (hello.o)
  4. The linker resolving symbols and creating the executable (hello)

Adding Input

Extend the program to accept user input:

#include <iostream>
#include <string>

int main() {
    std::string name;
    std::cout << "Enter your name: ";
    std::cin >> name;
    std::cout << "Hello, " << name << "!\n";
}

Compile and run:

g++ -std=c++17 -Wall input.cpp -o input
./input

Expected output:

Enter your name: Alice
Hello, Alice!

Note the >> operator reads from std::cin into a std::string. It stops at whitespace. Entering "Alice Smith" would only capture "Alice."

Chaining Stream Output

Multiple << operators can be chained:

#include <iostream>

int main() {
    int x = 42;
    double pi = 3.14159;
    std::cout << "x = " << x << ", pi = " << pi << "\n";
}

Expected output:

x = 42, pi = 3.14159

Each << returns the same stream, so the next << in the chain operates on it. This is why std::cout << a << b works: it is ((std::cout << a) << b).

Common Mistakes

Mistake 1: Missing #include <iostream>

Without the include, the compiler gives an error like error: 'cout' is not a member of 'std'. Always include the header before using the feature.

Mistake 2: Missing std::

Writing cout << "hello"; without std:: gives a compilation error. Either qualify with std:: or add using namespace std; (though the latter is discouraged in larger projects).

Mistake 3: Semicolons on #include Lines

#include <iostream>; is wrong. Preprocessor directives do not end with semicolons. The compiler will likely produce a confusing error.

Mistake 4: Wrong main Return Type

void main() is not valid C++ (though some compilers accept it). The standard requires int main(). Use int main() always.

Mistake 5: Forgetting the Newline

Without \n, output may not appear immediately because std::cout is buffered. Adding \n or std::flush forces the output buffer to be written to the terminal.

Mistake 6: Multiple Definitions of main

If you compile two .cpp files each with their own main, the linker errors with "multiple definition of main." A program can have exactly one main.

Practice Questions

  1. What does #include <iostream> do? Why is it necessary?
  2. What is the difference between \n and std::endl?
  3. What happens if you omit return 0; from main?
  4. Write a program that prints your name, age, and favorite color on three separate lines.
  5. Explain why std::cout << "A" << "B" prints "AB" rather than causing an error.

Challenge

Write a program that uses a single std::cout statement with chained << operators to print a diamond pattern of asterisks (3 rows tall). Do not use loops yet.

FAQ

Why does my terminal show a blinking cursor but no output?

The output is buffered. Either add \n at the end of your string or flush manually with std::flush or std::endl. std::endl inserts a newline and flushes.

Is `using namespace std;` bad?

It is acceptable in small programs and tutorials, but in larger projects it pollutes the global namespace. Always prefer std:: qualification in headers and production code.

What is the difference between `printf` and `std::cout`?

printf is the C-style function from <cstdio>. It is type-unsafe and not extensible. std::cout is type-safe, supports operator overloading, and can print user-defined types. Prefer std::cout in C++.

Can `main` return something other than `int`?

No. The standard mandates int main() or int main(int, char**). Some platforms accept void main() as an extension, but the resulting program is not portable.

What does `std::endl` do that `\n` does not?

std::endl inserts a newline and flushes the output buffer. \n only inserts a newline. Flushing is expensive, so prefer \n for most output and std::endl when you need immediate output (logs, progress indicators).

Why does my antivirus flag compiled C++ programs?

Some antivirus software flags small compiled executables as suspicious because they contain machine code that runs directly. This is a false positive. You can add your build directory to the antivirus exclusion list.

Mini Project

Write a program that asks the user for three integers, multiplies them, and prints the result. All input and output should use std::cin and std::cout. Compile with warnings enabled.

#include <iostream>

int main() {
    int a, b, c;
    std::cout << "Enter three numbers: ";
    std::cin >> a >> b >> c;
    int product = a * b * c;
    std::cout << "Product: " << product << "\n";
}

Expected output (with input 2, 3, 4):

Enter three numbers: 2 3 4
Product: 24

What's Next

You can now write and compile a C++ program. The next lesson covers variables, fundamental types, type deduction with auto, and the sizeof operator. You will learn how C++ represents data in memory.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro