Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 171 ยท Variables and Types

Variables

Declare and initialize C++ variables with =, () and {} braces, see why uninitialized variables are dangerous, assign new values and preview scope.

A variable is a named piece of memory that holds a value. When you write int score = 0;, you ask the compiler to set aside enough memory for a whole number, call it score, and put 0 in it. Later you can read the value, change it and use it in calculations. Variables are how programs remember things.

C++ is a statically typed language: every variable has a type that is fixed when you declare it and can never change. An int stays an int for its whole life. That strictness lets the compiler catch mistakes early and generate fast code. In this lesson you'll learn how to declare variables, the three ways to give them a starting value (and which one to prefer), why a variable without a starting value is one of C++'s classic traps, how assignment works, and where a variable can be used.

Declaring and initializing variables

A declaration introduces a variable: a type followed by a name. Initialization gives it its first value, right as it's created. You'll almost always do both at once:

C++ Your first variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

These are the types you'll use most often at first:

Type Holds Example
int Whole numbers int lives = 3;
double Numbers with a decimal part double price = 9.99;
char A single character, in single quotes char grade = 'A';
bool true or false bool done = false;
std::string Text, in double quotes (needs <string>) std::string name = "Ada";

You'll explore each type in detail in Fundamental Data Types. Note that std::string isn't built into the language; it's a class from the standard library, which is why it has the std:: prefix.

You must declare a variable before you use it. The compiler reads from top to bottom, so using age on a line above its declaration is an error: 'age' was not declared in this scope.

You can declare several variables of the same type in one statement, separated by commas:

C++
int width = 1920, height = 1080;

It's legal, but one declaration per line is easier to read and to change, so most style guides prefer it.

Three ways to initialize

C++ has grown several initialization syntaxes over the years. You'll see all of them in real code:

C++ =, () and {} initialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

For simple values like these, all forms produce the same result. The difference shows up when the value doesn't fit the type. Look what happens when a decimal number goes into an int:

C++ = and () silently lose data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

It prints 3 4 19. The decimal parts are simply thrown away, and with our flags (-Wall -Wextra) the compiler doesn't even warn. A conversion that can lose information like this is called a narrowing conversion. Braces don't allow it. This example fails on purpose:

C++ Braces reject narrowing (on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC stops with error: narrowing conversion of '3.7000000000000002e+0' from 'double' to 'int'. (That long number is just how GCC writes 3.7 in the error.) That error is a feature: if you really want to drop the decimals, you say so explicitly with a cast, which you'll learn in Type Conversions and Casts. For narrowing from another variable, like int whole{price};, the standard also forbids it; GCC reports it as a warning, and Clang and MSVC as an error.

So which form should you use? Reasonable modern guidance:

  • Braces {} are the safest default: they work for every type, reject narrowing, and {} alone gives a well-defined "zero" value. Many style guides recommend them, and this course uses them where they help.
  • = is the most readable for simple values (int lives = 3;), and you'll see it constantly. It's perfectly fine when the value obviously fits.
  • Parentheses () are mostly used to call specific constructors of classes, which comes later in Constructors.

Warning: int count(); with empty parentheses does not create a variable. It declares a function named count that returns int, a famous C++ quirk called the "most vexing parse". GCC warns: empty parentheses were disambiguated as a function declaration. Write int count{}; or int count = 0; instead.

You'll also meet auto, which lets the compiler deduce the type from the initializer: auto total = 0; makes an int. It's covered in Type Deduction with auto.

Uninitialized variables

You can declare a variable without giving it a value:

C++
int total;  // no initializer

For a local variable of a fundamental type like int or double, this does not set it to zero. The variable simply contains whatever bits happened to be in that memory. Reading it before assigning a value is undefined behavior: the program might print a random number, print 0, or behave in a way that makes no sense at all, and it can change between runs, compilers and optimization levels.

C++ Using an uninitialized variable (a bug!)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Look at the compiler output first: GCC warns 'total' is used uninitialized [-Wuninitialized] and points to the declaration. The printed number may look reasonable on our server, but nothing guarantees it. On another machine or with different flags, the same program can print something else entirely. That's what makes these bugs so nasty: they hide during testing.

The fix is simple and should become a reflex: initialize every variable when you declare it.

C++
int total = 0;   // or: int total{};
total += 5;      // now always 5

Not every type works this way. Class types like std::string and std::vector set themselves up properly even without an initializer: std::string name; is a valid empty string. And variables declared outside any function (globals) start at zero. But the rule "always initialize" never hurts, so just follow it everywhere.

Note: C++26 makes reading an uninitialized local variable "erroneous behavior" instead of undefined behavior, which limits the damage. It's still a bug, and compilers will keep warning about it.

Assignment: changing a value

After a variable exists, the assignment operator = replaces its value. The right side is evaluated first, then stored in the variable on the left:

C++ Assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Some things to understand here:

  • Initialization and assignment look similar but are different. int balance = 100; creates the variable with a value; balance = 250; changes an existing one. For classes the difference matters a lot, as you'll see in later lessons.
  • In C++, = means "store", not "is equal to". balance = balance - 75 is perfectly sensible: take the current value, subtract 75, store the result. Testing equality uses ==, covered in Comparison and Logical Operators.
  • Assignment copies the value. After int saved = balance;, the two variables are independent. Changing balance doesn't affect saved.
  • -= is a compound assignment operator; +=, *= and /= work the same way. More in Assignment and Increment Operators.

A variable's type can't change, so assigning a value of a different type converts the value (or fails to compile). int n = 0; n = 2.9; stores 2. And if a value should never change after initialization, mark it const: const int max_players = 4; makes any later assignment a compile error. You'll learn more in Constants.

Scope: where a variable lives

A variable's scope is the part of the program where its name can be used. A variable declared inside a block { } exists from its declaration to the end of that block. When the block ends, the variable is destroyed:

C++ Block scope and shadowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output shows that changes made inside the if block to the outer temperature stick (Temperature now: 21), while the inner block's temperature is a separate variable: printing 99 inside doesn't change the outer 21. Declaring a variable with the same name as one in an outer scope is called shadowing. It's legal, but it's a common source of confusion, so avoid it. GCC can warn about it with -Wshadow.

Uncomment the heating_minutes line and run to see the scope error. Good practice is to declare variables in the smallest scope possible, as close as you can to where they're first used. Small scopes make code easier to read and prevent accidental reuse. You'll study scope, lifetime and global variables properly in Scope, Lifetime and Storage Duration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int x = 5; int y = x; x = 10; std::println("{}", y);

    int y = x; copies the value 5 into y. Changing x afterwards doesn't affect y.
  2. 2. What happens with int items{2.5};?

    Braces reject conversions that lose information. int items = 2.5; would compile and silently store 2.
  3. 3. A function contains int count; std::println("{}", count);. What does it print?

    Local variables of fundamental types aren't initialized automatically. Reading count before assigning it is undefined behavior, and GCC warns about it.
  4. 4. What does int value(); declare?

    Empty parentheses are parsed as a function declaration (the "most vexing parse"). Use int value{}; for a zero-initialized variable.
  5. 5. What is printed? int n = 4; { int n = 7; n += 1; } std::println("{}", n);

    The inner n is a separate variable that shadows the outer one and is destroyed at the closing brace. The outer n is still 4.

Summary

  • A variable is a named, typed piece of memory. Declare it with a type and a name, and initialize it in the same statement.
  • Common starting types: int, double, char, bool and std::string.
  • Initialize with =, () or {}. Braces reject narrowing conversions and {} alone gives zero; int x(); declares a function, not a variable.
  • Reading an uninitialized local variable is undefined behavior: always initialize, and heed -Wuninitialized warnings.
  • Assignment = replaces a value (right side first) and copies values between variables; use const for values that must not change.
  • A variable exists from its declaration to the end of its block. Keep scopes small and avoid shadowing.

Next: Fundamental Data Types, where you'll explore bool, char, the integer family, floating-point types, sizeof and fixed-width integers.