Skip to content
Laviyx Learn

Try

C++ course menu

C++ Variables: Declaring, Initializing and Updating Values

Learn C++ variables: how to declare and initialize them, brace initialization with {}, the auto keyword, assigning new values, naming rules, why uninitialized variables are dangerous, and swapping two variables.

Beginner8 min readUpdated
On this page

A variable is a named place in memory that holds a value. In C++, every variable has a type that is fixed when you create it: an int always holds whole numbers, a double always holds decimal numbers, and so on.

Declaring and initializing#

To create a variable, write its type, its name, and (almost always) a starting value:

C++
#include <iostream>
#include <string>

int main() {
    int age = 21;
    double price = 49.99;
    char grade = 'A';
    bool is_member = true;
    std::string name = "Asha";

    std::cout << name << " is " << age << '\n';
    std::cout << "Price: " << price << ", grade: " << grade << '\n';
    std::cout << "Member: " << is_member << '\n';
}
Output
Asha is 21
Price: 49.99, grade: A
Member: 1

Giving a variable its first value is called initialization. Notice that bool values print as 1 and 0 by default. You will learn how to print true and false in Data Types.

Three ways to initialize#

C++ has several initialization styles, and you will see all of them:

C++
int a = 10;   // copy initialization
int b(10);    // direct initialization
int c{10};    // brace (uniform) initialization

Brace initialization ({}) is the modern recommendation, because it refuses narrowing conversions that would lose data:

C++
int main() {
    int count{3.7};   // error: narrowing conversion from double to int
}

With int count = 3.7; the compiler silently stores 3 (at best with a warning). Braces turn that silent bug into an error. In this course we use = for simple values, because it reads naturally, and braces when initializing collections and objects.

Changing a variable#

Assign a new value with =. The type stays the same:

C++
#include <iostream>

int main() {
    int score = 10;
    std::cout << score << '\n';

    score = 25;
    std::cout << score << '\n';

    score = score + 5;
    std::cout << score << '\n';
}
Output
10
25
30

score = score + 5 means "calculate score + 5, then store the result back in score". You can also write score += 5; see Operators.

auto: let the compiler choose the type#

With auto, the compiler works out the type from the initial value:

C++
#include <iostream>

int main() {
    auto items = 3;        // int
    auto weight = 2.5;     // double
    auto letter = 'x';     // char

    std::cout << items * weight << ' ' << letter << '\n';
}
Output
7.5 x

The variable is still strongly typed; auto only saves typing. It is most useful for long type names, which you will meet with the STL. For simple values, writing int or double is often clearer.

Declaring several variables#

You can declare several variables of the same type in one line, but give each its own value:

C++
int width = 4, height = 3;

One variable per line is usually easier to read.

Uninitialized variables are dangerous#

If you declare a local variable without a value, it contains whatever bits happened to be in memory:

C++
int total;           // no value!
total = total + 10;  // undefined behaviour: total could be anything

Reading an uninitialized variable is undefined behaviour: the program may print garbage, crash, or seem to work today and fail tomorrow. Always initialize, even if only with 0:

C++
int total = 0;

Compile with -Wall -Wextra and the compiler will warn about many of these mistakes.

Naming variables well#

Names follow the identifier rules from Syntax: letters, digits and _, not starting with a digit. Choose names that describe the value:

UnclearClear
xprice
n2student_count
tmpprevious_balance

Short names such as i and j are fine for loop counters.

Swapping two variables#

A classic task is swapping two values. You need a temporary variable, or the standard function std::swap:

C++
#include <iostream>
#include <utility>

int main() {
    int a = 1;
    int b = 2;

    int temp = a;
    a = b;
    b = temp;
    std::cout << a << ' ' << b << '\n';

    std::swap(a, b);
    std::cout << a << ' ' << b << '\n';
}
Output
2 1
1 2

Common mistakes#

Practice#

Practice exercise

Create variables for a product: its name ("Notebook"), its price (45.5) and the quantity in a cart (4). Print the product name and the total cost. Then increase the quantity by 2 and print the new total.

Show hint

Use std::string, double and int. The total is price * quantity.

Show solution
C++
#include <iostream>
#include <string>

int main() {
    std::string product = "Notebook";
    double price = 45.5;
    int quantity = 4;

    std::cout << product << ": " << price * quantity << '\n';

    quantity = quantity + 2;
    std::cout << product << ": " << price * quantity << '\n';
}
Output
Notebook: 182
Notebook: 273

std::cout prints 182, not 182.0, because it leaves out trailing zeros by default. You will learn to control decimal places in Data Types.

Key takeaway#

Finished this lesson?