C++ Variables

A variable in C++ is a named piece of memory with a type fixed at declaration, so the compiler knows its size and which operations are legal. In C++, every variable has a type that tells the compiler what kind of data it holds and how much memory to reserve. Getting comfortable with variables is the first real step toward writing useful programs.

Creating Variables

In C++ you must declare a variable with a type before you can use it. The most common types you will meet early on are int for whole numbers, double for decimal numbers, char for single characters, string for text, and bool for true/false values. The pattern is always the same: write the type, then a name, then optionally an equals sign and a starting value.

Declaring and printing a variable

#include <iostream>
using namespace std;

int main() {
  int age = 25;
  cout << "Age: " << age;
  return 0;
}

You can also declare a variable first and assign its value later. This is handy when the value is not known at the moment you create the variable.

Declare now, assign later

#include <iostream>
using namespace std;

int main() {
  int score;
  score = 90;
  cout << "Score: " << score << endl;
  score = 100;  // you can overwrite it
  cout << "New score: " << score;
  return 0;
}

Naming Rules

  • Names can contain letters, digits, and underscores.
  • Names must begin with a letter or an underscore, never a digit.
  • Names are case sensitive, so age and Age are two different variables.
  • Reserved keywords such as int, return, or double cannot be used as names.
Note: Choose descriptive names like totalPrice or userAge instead of x or t. Clear names make your code far easier to read and fix later.
TypeExample valueUsed for
int42Whole numbers
double3.14Decimal numbers
char'A'A single character
string"Hello"Text (needs <string>)
booltrueTrue or false

Exercise: C++ Variables

What must you specify when declaring a new variable in C++?