Variables, Data Types & Constants
A variable is a named storage location in your computer's RAM. Because C++ is statically typed, you must explicitly state what type of data a variable will store when you create it, and that type cannot change later.
Data Type Size (Typical) Description Example
int 4 bytes Whole numbers (positive or negative) int score = -42;
float 4 bytes Single-precision decimal numbers (up to ~7 digits) float temp = 36.6f;
double 8 bytes Double-precision decimal numbers (up to ~15 digits) double pi = 3.14159265;
char 1 byte A single ASCII character enclosed in single quotes char initial = 'J';
bool 1 byte Logical true (1) or false (0) values bool isActive = true;
std::string Dynamic Text sequences enclosed in double quotes (requires <string>) std::string role = "Admin";
• Variable Naming Rules: Names can contain letters, digits, and underscores (_), must not start with a digit, and cannot use reserved C++ keywords (like int, return, or class).
• Constants (const): When a value should never change while the program runs (such as tax rates, speed of light, or maximum lives), add the const keyword. Trying to modify a const variable later causes a compiler error.
#include <iostream> #include <string> int main() { const int MAX_LIVES = 3; // Cannot be modified later int currentLives = MAX_LIVES; double healthPercentage = 98.5; char rank = 'S'; bool isGameOver = false; std::string playerName = "Hero"; currentLives = 2; // Allowed because currentLives is not const // MAX_LIVES = 5; // ERROR! Cannot assign to a const variable std::cout << playerName << " (Rank " << rank << ") has " << currentLives << " lives left." << std::endl; return 0; }
Watch companion video on YouTube
Sign in to save your progress