# C++ basics: _a hands-on first tutorial_ C++ is a language where you tell the computer _exactly_ what to do, then compile your code into a program the machine runs directly. It powers browsers, games, operating systems, and the high-performance guts of almost everything fast. Bjarne Stroustrup created C++ in the early 1980s as an extension of C, adding _classes_ so that code could be organised around objects, which is where the "++" comes from (it's the C increment operator: "C, and then some").[1](#ref-1) This tutorial assumes you know _nothing_ about C++. Every new idea comes with a tiny, runnable example, and every language feature links to a reputable source, cppreference.com[2](#ref-2), the C++ Core Guidelines[3](#ref-3), and learncpp.com[4](#ref-4), so you can always read the authoritative version. You don't need to memorise anything. Read a section, type the example yourself (typing beats copy-pasting when you're learning), watch what happens, then move on. Let's begin. ## 01What C++ is, in one minute C++ is a **compiled language**. That's the big idea, and it's worth sitting with. With an interpreted language, a separate program reads your code line by line as it runs. With C++, you run a **compiler**: a tool like GCC, Clang, or MSVC, that translates your whole program into machine code _before_ you run it. The result is a standalone executable: fast, and independent of the language tools.[5](#ref-5) That compile-ahead step is exactly why C++ is the choice for things where speed and control matter. Two terms you'll meet immediately: - **Source file**: the plain-text file you write, traditionally named with a `.cpp` extension. - **Compiler**: the program that turns your `.cpp` into an executable. On most systems the standard command-line compilers are `g++` (GCC) or `clang++` (Clang).[6](#ref-6) ## 02Install a compiler You need a C++ compiler before any code will run. Which one depends on your system: - **Linux**: install the GNU compiler collection. On Debian/Ubuntu: `sudo apt install g++`. The `g++` command then compiles C++.[6](#ref-6) - **macOS**: install the Xcode command-line tools with `xcode-select --install`; that provides `clang++`. - **Windows**: the friendliest path is [learncpp.com](https://www.learncpp.com/)'s walkthrough, which recommends Visual Studio (with the "Desktop development with C++" workload) or MinGW-w64 / Clang.[4](#ref-4) The MSVC compiler ships inside Visual Studio. Verify it works by opening a terminal and running `g++ --version` (or `clang++ --version`). If it prints a version number, you're set. The current ISO standard is C++20, with C++23 published and compilers rolling out support, but everything in this tutorial works on any reasonably modern compiler.[7](#ref-7) ## 03Your first program Here is the smallest interesting C++ program. Don't worry that it looks dense, we'll take it apart line by line. ``` #include int main() { std::cout << "Hello, world!"; return 0; } ``` Save it as `hello.cpp`, then compile and run: ``` # compile g++ hello.cpp -o hello # run ./hello ``` That prints `Hello, world!`. Now the line-by-line: - `#include ` pulls in the standard _input/output stream_ library, which defines `std::cout` (the screen) and `std::cin` (the keyboard). The preprocessor inserts that library's declarations before compiling.[8](#ref-8) - `int main()` defines `main`, the function every C++ program must have. Execution starts here. `int` means it returns an integer.[9](#ref-9) - `std::cout << "Hello, world!";` sends the text to the screen. The `<<` is the _stream insertion_ operator: "push this into the output stream."[10](#ref-10) - `return 0;` ends `main` and tells the operating system the program finished successfully. By convention, `0` means "all good."[9](#ref-9) - Every statement ends with a semicolon `;`. In C++, the semicolon is the full stop of a command, forget it and the compiler will complain.[11](#ref-11) > **Reading a compiler error is a skill.** Your first few compiles will throw red errors. Read the _first_ one: it names the file and line, and usually the real problem is there or just above. The later errors are often echoes of the first. This is normal; every C++ programmer lives here at the start. ## 04Variables and types In C++ you must declare a variable's **type** when you create it. The type tells the compiler how much memory to set aside and what operations are allowed. Unlike Python, types are fixed at compile time: this is what "statically typed" means, and it's a big reason C++ is fast and catches whole classes of bugs early.[12](#ref-12) The everyday built-in types: ``` int age = 30; // whole numbers double price = 9.99; // decimals (double-precision float) float ratio = 0.5f; // decimals (single-precision) bool open = true; // true / false char letter= 'A'; // a single character std::string name = "Ada"; // a sequence of characters ``` A few things worth noticing: - `int` is the workhorse integer type; `double` is the usual floating-point type. The Core Guidelines suggest preferring `double` over `float` unless you have a space reason not to.[3](#ref-3) - `std::string` lives in ``, so you'd add `#include ` to use it.[13](#ref-13) - Modern C++ (C++11 and later) lets you write `auto count = 0;` and let the compiler deduce the type, but for learning, naming the type explicitly keeps things clear.[14](#ref-14) You can change a variable's value later by assigning again, but you can't change its _type_: ``` age = 31; // fine // age = "thirty"; // error: age is an int, not text ``` ## 05Output and input: cout and cin You've met `std::cout` for output. You can chain several `<<` to build a line, and end with `std::endl` (or `"\n"`) to drop to a new line.[10](#ref-10) ``` std::cout << "You are " << age << " years old." << std::endl; ``` For input, use `std::cin` with the _extraction_ operator `>>`. Whatever the user types flows into your variable: ``` int year; std::cout << "Birth year: "; std::cin >> year; // reads an integer from the keyboard std::cout << "Approx age: " << (2026 - year) << std::endl; ``` One gotcha for later: `std::cin >> year` reads a number, but if the user types letters it goes wrong. Real programs check input, we'll handle that properly in Part 2 (intermediate). ## 06Doing maths The arithmetic operators are what you'd expect: `+` `-` `*` `/`, plus `%` (modulo, the remainder after division).[15](#ref-15) ``` int a = 17, b = 5; std::cout << (a + b) << " " // 22 << (a / b) << " " // 3 (integer division drops the fraction) << (a % b) << std::endl; // 2 (remainder) ``` Watch the integer-division trap: `17 / 5` is `3`, not `3.4`, because both numbers are `int`. To get the decimal, make at least one a `double`: `17.0 / 5` → `3.4`. ## 07Making decisions with if A program that can't choose isn't much of a program. The `if` statement runs a block only when a condition is true. Conditions use comparison operators: `==` (equal, note the double equals), `!=` (not equal), and `` `=`.[16](#ref-16) ``` if (age >= 18) { std::cout << "You can vote." << std::endl; } else { std::cout << "Not yet." << std::endl; } ``` Curly braces `{ }` mark a block. For a single statement you can omit them, but keeping the braces is a habit the Core Guidelines explicitly recommend, it prevents the classic "I added a line and it silently fell outside the if" bug.[3](#ref-3) You can chain alternatives with `else if`. ## 08Repeating with loops Computers are brilliant at repetition, and C++ gives you two main loops. A `for` loop repeats a known number of times; a `while` loop repeats as long as a condition holds.[17](#ref-17) ``` // count 1 to 5 for (int i = 1; i <= 5; i = i + 1) { std::cout << i << " "; } ``` The `for` header reads almost like English: start `i` at 1; keep going while `i <= 5`; each turn add 1 to `i`. A `while` loop is better when you don't know the count up front, say, "keep asking until the answer is right." ``` int n = 0; while (n < 3) { std::cout << "n is " << n << std::endl; n = n + 1; } ``` ## 09Grouping code into functions When you find yourself writing the same few lines again and again, wrap them in a **function**: a named, reusable block. You've already used one (`main`); now write your own with the `int`/`void` return type, the name, and parentheses.[18](#ref-18) ``` int square(int x) { return x * x; } // later, in main: std::cout << square(4) << std::endl; // prints 16 ``` `square` takes an `int` called `x` and `return`s its square. Functions make programs readable and testable: each piece does one job, and you can reason about it in isolation. The Core Guidelines put it plainly, "organise programs around functions and interfaces," and keep functions small and focused.[3](#ref-3) ## 10A first small project: a number-guessing game Let's combine everything into a real, runnable program. The computer picks a number; the player guesses; it says "too high" or "too low" until they win. We'll use a simple pseudo-random number (a fuller version with proper seeding comes in Part 2). ``` #include #include // for rand() and srand() #include // for time() int main() { std::srand(time(nullptr)); // seed the generator int secret = std::rand() % 20 + 1; // 1..20 int guess, tries = 0; std::cout << "I'm thinking of a number from 1 to 20.\n"; while (true) { std::cout << "Your guess: "; std::cin >> guess; tries = tries + 1; if (guess < secret) std::cout << "Too low.\n"; else if (guess > secret) std::cout << "Too high.\n"; else { std::cout << "Correct in " << tries << " tries!\n"; break; // leave the loop } } return 0; } ``` Read it slowly and you'll recognise every piece: `#include` for the libraries, `main`, variables with types, `std::cin`/`std::cout`, `if`/`else if`/`else`, a `while (true)` loop ended by `break`, and `return 0`. That's a genuine, interactive program, and you now understand every line of it. > The random number here uses `std::rand()`, which is simple but low-quality and now discouraged for serious use. C++11 introduced `` with proper engines like `std::mt19937`. We'll switch to it in Part 2, for a first project, `rand()` keeps the focus on the logic.[19](#ref-19) ## 11Where to go next You've covered the true fundamentals: compiling, variables and types, input/output, arithmetic, decisions, loops, and functions. That's most of what any C++ program is built from. Everything else (the standard library, classes, memory, templates) is more of the same, plus powerful new ideas. - **Practise more than you read.** Programming is a skill like an instrument; understanding a chord isn't the same as playing one. Retype the examples, break them on purpose, and fix them. - **Work the reputable tutorials next.** [learncpp.com](https://www.learncpp.com/) is a free, modern, and widely recommended C++ course.[4](#ref-4) The C++ Core Guidelines are the community's agreed best practices, maintained by Bjarne Stroustrup and Herb Sutter.[3](#ref-3) - **Keep a reference open.** When you forget a detail, cppreference.com is the definitive C++ reference, dense, but authoritative.[2](#ref-2) - **Write readable code.** The Core Guidelines' spirit is simple: code is read far more often than it's written. Small functions, clear names, braces on every block. Everyone who writes C++ fluently once stared at their first `Hello, world!` and a wall of compiler errors. The distance from here to there is just practice, and you've already taken the first steps. > **About this piece.** This is Part 1 (Basics) of a three-part C++ series from OcxlyDev, followed by [Part 2: Intermediate](cpp-intermediate.html) and [Part 3: Advanced](cpp-advanced.html). Every language feature links to a reputable primary source below, so you can always read the authoritative version. The fundamentals here have been stable across modern C++ standards (C++11 through C++20/23) and aren't going anywhere. Ready for the next step? Continue with the intermediate tutorial. ## References - Bjarne Stroustrup — C++ FAQ (the origins of C++ as "C with Classes", early 1980s) - cppreference.com — C++ reference (definitive language and standard-library documentation) - Bjarne Stroustrup & Herb Sutter — C++ Core Guidelines (community best-practice rules; P.1, ES.1, etc.) - learncpp.com — free, modern C++ tutorial (recommended starting course) - cppreference.com — C++ language (compilation model, translation units, the compilation process) - GNU Compiler Collection — Invoking g++ (the standard C++ compiler driver) - ISO C++ Foundation — The C++ Standard (current and draft standards, C++20 / C++23) - cppreference.com — <iostream> (the standard input/output stream library) - cppreference.com — Main function (program entry point, return type and convention) - cppreference.com — std::cout (the standard output stream and the << operator) - cppreference.com — Statements (semicolons, compound statements, and the grammar) - cppreference.com — Type (static typing, type categories, and declarations) - cppreference.com — std::basic_string (the std::string class in <string>) - cppreference.com — auto specifier (type deduction, since C++11) - cppreference.com — Arithmetic operators (+, -, *, /, %, and integer division) - cppreference.com — if statements (selection, comparison operators, else/else if) - cppreference.com — for and while statements (iteration and loops) - cppreference.com — Functions (declaration, parameters, and return) - cppreference.com — Pseudo-random number generation (<random>, std::mt19937, superseding std::rand)