C++ · Chapter 3 of 49

C++ Get Started

Every C++ program needs a `main()` function — this is where execution begins. The program returns an integer exit code, usually 0 to mean success.

Headers like `<iostream>` are included with `#include` so you can use library features such as input/output.

Anatomy of a program

`#include <iostream>` brings in the I/O library. `int main() { ... }` is the entry point. Statements inside main run in order, and `return 0;` ends the program successfully.

Compiling and running

Save the file with a `.cpp` extension, compile it with g++, then execute the produced binary. Any compiler errors must be fixed before you get an executable.

Example 1 (cpp)
#include <iostream>
int main() {
    std::cout << "Hello from main!" << std::endl;
    return 0;
}
Output
Hello from main!

std::endl prints a newline and flushes the output buffer.

Key points

  • Every program needs exactly one main() function.
  • main() typically returns an int (0 = success).
  • #include brings library code into your file.
  • Statements execute top-to-bottom inside main.
💡 Note: Returning 0 from main is optional in C++ (it defaults to 0), but writing it explicitly is good practice.

📝 Quick Quiz

1. Where does a C++ program start executing?

2. What does returning 0 from main usually mean?

3. Which statement includes the I/O library?