Variables
A free lesson from Swipe Coding · C++, level 2 · updated October 2026
By the Swipe team, founded by Colin · how we make lessons
A variable is a named container that stores a piece of data your program can work with and change while it runs. In C++, every variable must have an explicit type, so the compiler always knows exactly what kind of data it is allowed to hold and how much memory to set aside for it.
int age = 25; std::cout << age << std::endl;
The general pattern for declaring and initializing a variable is: type name = value;. Here, int is the type, age is the name, and 25 is the value assigned with the = operator. You don't have to assign a value right away — you can declare a variable first and assign it later.
Here is something to watch out for: unlike some other languages, C++ does NOT automatically give a local variable a safe default value. If you declare a variable without initializing it and then use it, it contains whatever leftover, unpredictable data already happened to be sitting in that spot in memory. This is called undefined behavior, and it compiles just fine — the bug only shows up when the program runs. Always initialize your variables.
int score; // dangerous: not initialized std::cout << score << std::endl; // could print anything int safeScore = 0; // always initialize instead std::cout << safeScore << std::endl; // reliably prints 0
If you declare a variable in C++ without giving it a value, C++ automatically sets it to a safe default like 0.
Variable names in C++ must start with a letter or an underscore (_) — never a digit — and cannot be one of C++'s reserved keywords (like int or class). Names are case-sensitive, so score and Score are two different variables. By convention, this course writes variable names in camelCase: the first word lowercase, and each following word starting with a capital letter, e.g. totalScore or firstName.
By convention, variable names in this course use ____, where the first word is lowercase and every following word starts with a capital letter, such as totalScore.
A variable can also be reassigned: given a new value after it was already initialized. The new value simply replaces the old one — the old value is gone. You never repeat the type when reassigning, only when first declaring the variable.
int lives = 3; lives = lives - 1; std::cout << lives << std::endl; // 2
Keep your streak going in Swipe Coding
Swipe through every level of C++ on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.
Get the Swipe apps →