TExcelTAD
Home › C++ › C++ Variables

C++ Variables

A variable is a named piece of memory that holds a value. In C++ every variable has a type that is fixed when you declare it: an int always holds whole numbers, a std::string always holds text. The compiler uses the type to decide how much memory to reserve and which operations are allowed.

Declaring variables

The general form is type name = value;

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

int main() {
    int age = 29;
    double height = 1.74;
    char grade = 'A';
    string city = "Hanoi";
    bool likesTea = true;

    cout << "Age: " << age << "\n";
    cout << "Height: " << height << " m\n";
    cout << "Grade: " << grade << "\n";
    cout << "City: " << city << "\n";
    cout << "Likes tea: " << likesTea << "\n";
}
Age: 29
Height: 1.74 m
Grade: A
City: Hanoi
Likes tea: 1
Type Holds Example
int Whole numbers 42, -7
double Floating-point numbers 3.14, -0.5
char One character (single quotes) 'x'
std::string Text (double quotes, needs <string>) "Hello"
bool true or false (printed as 1 / 0) true

Changing a value

A variable can be given a new value at any time with =. The old value is simply overwritten:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    int score = 10;
    cout << score << "\n";
    score = 25;
    cout << score << "\n";
    score = score + 5;
    cout << score << "\n";
}
10
25
30

Ways to initialise

C++ has several initialisation syntaxes. The brace form (C++11) is often recommended because it refuses narrowing conversions that would lose data:

cpp
int a = 5;      // copy initialisation
int b(5);       // direct initialisation
int c{5};       // brace (uniform) initialisation
int d{};        // value-initialised to 0
int e{4.7};     // ERROR: narrowing double -> int is not allowed with {}

Warning: A local variable declared without an initial value, such as int x;, contains garbage — whatever bits happened to be in memory. Reading it is undefined behaviour. Always initialise your variables.

Declaring several variables

You can declare multiple variables of the same type in one statement, or give several variables the same value:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    int x = 3, y = 4, z = 5;
    cout << x + y + z << "\n";

    int a, b, c;
    a = b = c = 7;   // assignment is evaluated right to left
    cout << a << " " << b << " " << c << "\n";
}
12
7 7 7

Constants

Add const when a value must never change. The compiler then rejects any attempt to modify it:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    const double VAT = 0.10;
    const int DAYS_PER_WEEK = 7;
    double price = 50.0;
    cout << "With VAT: " << price * (1 + VAT) << "\n";
    cout << "Hours per week: " << DAYS_PER_WEEK * 24 << "\n";
    // VAT = 0.2;  // error: assignment of read-only variable
}
With VAT: 55
Hours per week: 168

constexpr goes one step further: the value must be known at compile time, e.g. constexpr int MAX_USERS = 100;.

Naming rules

  • Names may contain letters, digits and underscores, and must not start with a digit.
  • Names are case-sensitive (total and Total differ).
  • Keywords such as int, class or return cannot be used as names.
  • Choose descriptive names: secondsElapsed beats s. Common styles are camelCase and snake_case.

Test yourself

Which type should you use to store the text "Hello"?

  1. char
  2. std::string
  3. int
  4. bool

What does int n; (inside a function) contain before you assign it?

  1. 0
  2. -1
  3. An indeterminate garbage value
  4. It does not compile

Which name is NOT a valid variable name?

  1. total_sum
  2. _count
  3. 2ndPlace
  4. userAge