Thuta Learning
C++
BasicProgrammingBeginner

Variables

C++Lesson 525 min

What you'll walk away with

  • Declare, initialize and print variables of the basic types
  • Use brace initialization and explain the narrowing error it gives you
  • Explain why an uninitialized local variable is a bug and how to avoid it
  • Choose correctly between auto, an explicit type, const and constexpr
  • Follow C++ naming rules and pick readable names

Explain it simply

Explain it simply

A variable is a named piece of memory that holds one value of one type. When you write int age{20};, you ask for a slot big enough for an int, label it age and put 20 in it. Later you can read the value, print it or replace it with a new one, but the type stays int for the variable's whole life.

The type is the part that surprises people coming from Python or JavaScript. In C++ a variable cannot hold a number now and text later. That rule lets the compiler catch mistakes early, and it lets it pick exactly the right amount of memory and the right machine instructions for each value.

Problem → Why → Solution

The problem: values that quietly change or were never set

Two bugs show up in almost every beginner's first C++ programs. The first is a variable declared without a value and then used: a local int with no initializer holds whatever bits were left in that memory, so a running total can start from some random number. The second is a value that changes as it is stored: put 19.99 into an int and you get 19, with no error message unless you ask for extra warnings.

two_bugs.cpp
#include <iostream>

int main() {
    int total;              // no value yet: reading it is undefined behavior
    total += 5;
    int price = 19.99;      // compiles: the .99 is silently dropped
    std::cout << total << ' ' << price << '\n';
}

Why does C++ allow this?

C++ inherited C's rule that local variables of built-in types are not set to zero automatically, because zeroing costs time and the language avoids hidden work. It also inherited C's implicit conversions, so a double can be squeezed into an int. With -Wall, GCC does warn that total is used uninitialized, but the price line passes -Wall -Wextra silently; only -Wconversion reports it. The modern fix is to always initialize, and to use braces, which turn the price line into a compile error.

Core concept: declare, initialize, then use

A declaration names a type and a variable: int lessons; An initializer gives it its first value in the same statement. C++ has several spellings for that, and you will meet all of them in real code: int a = 5; (copy initialization, from C), int b(5); (direct initialization) and int c{5}; (brace or list initialization, added in C++11). For simple types they all produce the same value.

Braces are the modern default for one reason: they refuse narrowing conversions, which lose information. int price{19.99}; does not compile; GCC reports "narrowing conversion of '1.9989999999999998e+1' from 'double' to 'int'". That odd number is how GCC prints the double closest to 19.99, a hint that the value was never exact in the first place. Empty braces value-initialize: int count{}; is guaranteed to start at 0.

auto asks the compiler to deduce the type from the initializer: auto lessons = 35; is an int and auto ratio = 0.5; is a double. auto requires an initializer, so it also protects you from uninitialized variables. Be careful with text: auto name = "Thuta"; deduces const char*, a pointer to characters, not std::string.

const makes a variable read-only after initialization; assigning to it later is a compile error. constexpr goes further: the value must be known at compile time, so constexpr int maxSeats{40}; can be used where the compiler needs a constant, such as an array size. Use const for values computed while the program runs and constexpr for fixed constants.

Initialization and assignment are different operations that look alike. int score{70}; creates the variable and gives it its first value, while score = 80; replaces the value of a variable that already exists. That difference is why a const variable can be initialized but never assigned. For class types such as std::string the two jobs are also separate pieces of code. Giving the real value at the point of declaration is therefore simpler, and often faster, than creating an empty variable and filling it in afterwards.

Mental model: a labelled box with a fixed shape
  1. Type picks the box's size and shape
  2. The name is the label you refer to
  3. The initializer fills it right away
  4. const seals the lid after filling

A box with no initializer is not empty; it holds leftover bits.

General pattern: declaring variables

cpp
Type name{value};            // brace initialization (preferred)
Type name = value;           // copy initialization
Type name{};                 // value-initialized: 0, 0.0, false, ""
auto name = value;           // type deduced from the value
const Type name{value};      // read-only after initialization
constexpr Type name{value};  // must be known at compile time
name = newValue;             // assignment: replace the value later

Every declaration has a type (or auto) and a name, and should have an initializer. The last line is not a declaration: an assignment without a type replaces the value of a variable that already exists.

Example: Thuta's profile

This program initializes seven variables of different types with braces, including one constexpr constant and one auto variable. It prints a bool once the default way and once with std::boolalpha, and finally changes a value with an assignment. Predict all six output lines, especially the two bool lines.

profile.cpp
#include <iostream>
#include <string>

int main() {
    std::string name{"Thuta"};
    int age{20};
    double height{5.8};
    char grade{'A'};
    bool isLearning{true};
    constexpr int passMark{50};
    auto lessonsDone = 4;              // deduced as int

    std::cout << name << " is " << age << " years old.\n";
    std::cout << "Height: " << height << '\n';
    std::cout << "Grade: " << grade << '\n';
    std::cout << "Learning C++: " << isLearning << '\n';
    std::cout << std::boolalpha << "Learning C++: " << isLearning << '\n';

    lessonsDone = lessonsDone + 1;     // assignment replaces the value
    std::cout << "Lessons done: " << lessonsDone << ", pass mark: " << passMark << '\n';
    return 0;
}

Code breakdown

  1. Line 5std::string name{"Thuta"};

    Braces work for class types such as std::string too. The <string> header must be included.

  2. Line 8char grade{'A'};

    Single quotes make one character. With double quotes, char grade{"A"}; fails to compile, because "A" is a string literal.

  3. Line 10constexpr int passMark{50};

    A fixed value known at compile time. Writing passMark = 60; later is a compile error.

  4. Line 11auto lessonsDone = 4;

    4 is an int literal, so lessonsDone is an int. auto is not a dynamic type: the type is decided once, on this line, and never changes.

  5. Lines 16-17std::cout << std::boolalpha << "Learning C++: " << isLearning << '\n';

    By default std::cout prints a bool as 1 or 0. Sending std::boolalpha once makes later bools print as true and false; the setting stays on std::cout.

  6. Line 19lessonsDone = lessonsDone + 1;

    An assignment, with no type. The right side is evaluated first (4 + 1) and the result, 5, goes back into the box.

You should see
Thuta is 20 years old.
Height: 5.8
Grade: A
Learning C++: 1
Learning C++: true
Lessons done: 5, pass mark: 50

Comparing the initialization forms

FormExamplePutting 2.5 into an int
Copyint a = 2.5;Compiles; a becomes 2
Directint b(2.5);Compiles; b becomes 2
Braceint c{2.5};Narrowing compile error
Empty bracesint d{};No value needed: d is 0

GCC only warns about narrowing from a variable

The standard makes every narrowing inside braces ill-formed. GCC, though, gives an error when the source is a constant like 2.5 but only a warning for a variable, as in double price{1.5}; int whole{price};. Compile with -Werror and that warning becomes an error too, so with this course's -Wall -Wextra -Werror command every narrowing stops the build.

Naming rules and scope

  • Names may contain letters, digits and underscores but cannot start with a digit: 2ndPlace is invalid, secondPlace is fine.
  • C++ is case-sensitive: score and Score are two different variables.
  • Keywords such as int, class, new and return cannot be used as names.
  • Avoid names containing a double underscore or starting with an underscore and a capital letter; they are reserved for the compiler and library.
  • Pick camelCase or snake_case and use it consistently across a project.

A variable lives from the line that declares it to the closing brace of its block; that region is its scope. Below, bonus is declared in an inner block, so using it after the block makes GCC report "'bonus' was not declared in this scope". Declare variables as close as possible to where you first use them.

scope.cpp
#include <iostream>

int main() {
    int score{70};
    {
        int bonus{5};                  // bonus exists only inside these braces
        score = score + bonus;
    }
    // bonus is gone here: using it would be a compile error
    std::cout << "Score: " << score << '\n';
    return 0;
}

In real projects

Variables in real codebases

Professional code uses const by default: every value that never changes after initialization is marked const, so a reader only has to track the few variables that do change. Configuration constants such as buffer sizes, retry limits and timeouts are written with constexpr, replacing the #define macros found in older code, because a constexpr variable has a type and a scope.

auto is used where type names get long, such as iterators and std::chrono durations, while explicit types stay where they carry meaning, such as int or double. The C++ Core Guidelines rule ES.20, "Always initialize an object", is checked automatically by tools such as clang-tidy's cppcoreguidelines-init-variables check, and many teams run those checks in continuous integration.

Common mistakes

Common mistakes with variables

1. Reading a variable before giving it a value

Compile int total; total += 5; with -Wall and GCC warns "'total' is used uninitialized". With warnings off, the program simply carries on with a random number. Writing int total{}; makes it start at 0.

2. Mixing up single and double quotes

char grade = "A"; fails with "invalid conversion from 'const char*' to 'char'", because double quotes make a string literal. The reverse, std::string name = 'Thuta';, gives a multi-character literal warning and a conversion error. Use 'A' for one character and "Thuta" for text.

3. Expecting auto to give you a std::string

After auto name = "Thuta";, try name + " Aung": GCC reports "invalid operands of types 'const char*' and 'const char [6]' to binary 'operator+'", because two pointers cannot be joined with +. When you want text you can grow and join, write the type: std::string name{"Thuta"};.

4. Relying on std::string without #include <string>

With GCC, <iostream> happens to pull in <string>, so a program that uses std::string without including it may compile. The standard does not guarantee this, so it can break with another compiler or library version. Include the header for everything you use.

Best practices

Best practices

  • Initialize every variable where you declare it; use {} when the real value comes later.
  • Make brace initialization your default so the compiler catches narrowing.
  • Mark values that never change const, and compile-time constants constexpr.
  • Give names that say what they hold, such as score or totalPrice; keep names like x, temp and data for tiny scopes.

Mini challenge

Mini challenge: a tea shop order

Declare the variables for one tea shop order and print the total including tax. Then change the quantity and print it again.

  • A constexpr tax rate (the double 0.05) and a const std::string item name
  • An int quantity and a double unitPrice, both initialized with braces
  • An auto subtotal computed from quantity * unitPrice, then print the total including tax
  • Change quantity with an assignment, recompute subtotal and print again
order.cpp
#include <iostream>
#include <string>

int main() {
    // TODO: constexpr tax rate 0.05 and a const std::string item name
    // TODO: quantity (int) and unitPrice (double), both with braces

    // TODO: auto subtotal = ...; print "<item> x<quantity> = <total with tax>"

    // TODO: assign a new quantity, recompute subtotal, print again
    return 0;
}

Expected: With Milk tea at a unit price of 1.50: Milk tea x2 = 3.15 Milk tea x4 = 6.3

Show hint

int * double gives a double, so auto makes subtotal a double. The total with tax is subtotal * (1 + taxRate). Try assigning to the const item later and see what the compiler says.

Show solution
order.cpp
#include <iostream>
#include <string>

int main() {
    constexpr double taxRate{0.05};
    const std::string item{"Milk tea"};
    int quantity{2};
    double unitPrice{1.50};

    auto subtotal = quantity * unitPrice;      // int * double gives a double
    std::cout << item << " x" << quantity << " = " << subtotal * (1 + taxRate) << '\n';

    quantity = 4;                              // assignment: new value, same type
    subtotal = quantity * unitPrice;
    std::cout << item << " x" << quantity << " = " << subtotal * (1 + taxRate) << '\n';
    return 0;
}

Quick quiz 1 / 3

Which declaration fails to compile?

Quick quiz 2 / 3

What is the type of x in auto x = "Hi";?

Quick quiz 3 / 3

What does int count{}; count = count + 3; const int limit{count * 2}; std::cout << count << ' ' << limit; print?

What to remember

  • A variable has one fixed type, a name and a value; the type never changes.
  • Brace initialization refuses narrowing and {} gives 0; reading an uninitialized local is undefined behavior.
  • auto deduces the type from the initializer, and "text" gives const char*, not std::string.
  • const means read-only at run time; constexpr requires a value known at compile time.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Variables | Thuta Learning