Why learn C++?
You already know some Python, so you know what variables, loops, and functions are. C++ gives you the same ideas with two big differences: it is compiled, and it is statically typed. In exchange it runs 10 to 100 times faster than Python, which is why game engines, operating systems, trading systems, and browsers are written in it. It is also a favorite language for coding interviews because it is fast and its standard library maps cleanly onto data structures and algorithms.
In Python you run a program by handing the source file to an interpreter, which reads it line by line while the program runs. C++ works in two separate steps:
- A compiler (a program such as
g++orclang++) reads your whole.cppfile and translates it into machine code, the raw instructions your CPU executes. The result is a standalone executable file. - You run that executable. The compiler is no longer involved.
This is the single most important mental-model shift from Python: errors can now happen at compile time (the compiler refuses to produce an executable) or at run time (the executable misbehaves).
Anatomy of the smallest program
#include <iostream> int main() { std::cout << "Hello, C++!\n"; return 0; }
Line by line:
#include <iostream>pulls in the input/output stream library so you can print. It is roughly Python'simport, done before compilation.int main() { ... }is the entry point. Every C++ program starts by runningmain. Python starts at the top of the file, C++ always starts here.std::coutis the standard output stream (character out).std::means it lives in the standard library's namespace.<<sends what is on its right into the stream on its left.\nis a newline character.return 0;tells the operating system the program finished successfully.- Every statement ends with a semicolon, and blocks are wrapped in
{ }instead of using indentation.
Code exercise · cpp
Run the classic first program exactly as written. Press Run and confirm the output matches.
Quiz
You make a typo in a C++ program, like forgetting a semicolon. When do you find out?
Code exercise · cpp
Your turn. Edit the program so it prints two lines: first `Hello, C++!` and then `Goodbye, Python.` (each on its own line). Remember: one statement per line, each ending in a semicolon, and \n for the newline.