Variables are essentially labeled containers that store data in your computer's memory. Because C++ is a statically-typed language, you must tell the compiler exactly what kind of data a variable will hold before you use it. This allows the computer to reserve the correct amount of space in memory.
1. Common Data Types
Here are the primary types you'll use 90% of the time:
Type DescriptionSize (Typical)Example
intIntegers (whole numbers)4 bytesint age = 25;
doubleFloating-point (decimals)8 bytesdouble price = 19.99;
charSingle characters1 bytechar grade = 'A';
stringSequence of textVariablestring name = "Gemini";
boolBoolean (true/false)1 bytebool isCoding = true;
2. Declaration vs. Initialization
Declaration: Telling the compiler the name and type (e.g.,
int score;).Initialization: Giving that variable its first value (e.g.,
score = 100;).You can do both at once:
int score = 100;.
#include <iostream>
#include <string> // Required to use the string data type
using namespace std;
int main() {
// 1. Variable definitions
string playerName = "Alex";
int health = 100;
double shieldEnergy = 75.5;
char rank = 'S';
bool isGameOver = false;
// 2. Performing an operation
int damage = 20;
health = health - damage; // Updating the variable
// 3. Outputting the data
cout << "Player: " << playerName << endl;
cout << "Rank: " << rank << endl;
cout << "Health: " << health << "%" << endl;
cout << "Shield: " << shieldEnergy << " units" << endl;
// Boolean outputs 1 for true, 0 for false
cout << "Game Over? " << isGameOver << endl;
return 0;
}Key Rules for Naming (Identifiers)
Names can contain letters, digits, and underscores.
They must begin with a letter or an underscore (
_).C++ is case-sensitive (
myVarandmyvarare different).You cannot use "Keywords" (like
int,return, orclass) as names.