CppYour First Program

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

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::cout and std::cin.

  • int main() — every C++ program must have exactly one main function; it's the entry point where execution begins. The int means it returns an integer.

  • std::cout << "Hello, World!" << std::endl; — sends text to standard output. std::cout is the output stream, << is the "insertion operator" that feeds data into it, and std::endl ends 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

CPP
#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}
Avoid using namespace std; at global scope
This shortcut is common in small tutorials, but most style guides discourage it in real projects. The C++ standard library is huge, and pulling every name from `std` into the global scope makes it easy for names to silently collide with your own code or with other libraries — a bug that can be very confusing to track down. Prefer writing `std::cout` explicitly, or at most use targeted declarations like `using std::cout;` for names you use constantly.
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!