Create your own
Lesson illustration

Declaring and Updating Variables in C++

Welcome back. In the previous lesson, you used std::cout to display text and fixed numeric values such as 30. Fixed values are useful for testing, but programs become much more useful when they can give important values names, reuse them, and change them as the program runs.

In this lesson, you will declare variables, initialize them safely, choose among several fundamental C++ types, and update stored values. You will apply all of that in a small study-session tracker program—the same pattern that later programs will use for temperatures, calculator values, scores, and user input.


Variables: named storage for program data

A variable is a named place for one value of a particular type. Its type tells C++ what kind of value belongs there.

For example:

int studyMinutes { 30 };

This declares a variable called studyMinutes and gives it the whole-number value 30.

The diagram breaks `int age = 16;` into a data type (`int`), variable name (`age`), and initial value (`16`). The same three roles appear in every basic variable declaration.

The image uses this syntax:

int age = 16;

That is valid C++. It creates an int variable named age and gives it the initial value 16.

In this course, prefer brace initialization instead:

int age { 16 };

The braces make the initialization visually clear and help C++ catch some accidental data loss, which you will see shortly.

A useful way to read the statement is:

PartMeaning
intThe variable holds whole numbers.
studyMinutesThe name you will use to access that value.
{ 30 }The starting value.
;Ends the C++ statement.

A variable is not a mathematical equation. It is closer to a labeled location in your program’s working data. At any moment, a normal variable holds one current value.

Before writing more code, get a quick visual overview of the essential types and the declaration-and-update pattern.

Learn C++ With Me #3 - Data Types and Variables

Watch “Learn C++ With Me #3 - Data Types and Variables” by Tech With Tim for a visual introduction to the types and variable syntax you will use today. Focus on the distinction between whole numbers, decimal numbers, Boolean values, and single characters, then watch how values are assigned and changed.

Watch numeric and Boolean types for int, decimal types, and bool. Then skip to the char distinction for the difference between a character in single quotes and text in double quotes. Next, watch a declaration, where a typed variable is created and printed. Continue through type mismatch to see why storing a decimal in an integer can lose information. Finish with naming rules and updates and copies. Notice that the type appears when the variable is created, but not when its value is changed later.


Choosing a fundamental type

C++ provides several fundamental types. For now, choose based on the meaning of the value, not on its internal memory size.

TypeStoresExamples
intWhole numbers0, 27, -4
doubleDecimal numbers, with high precision18.5, -2.75
floatDecimal numbers, with less precision than double18.5F
boolA logical valuetrue, false
charOne character'A', '?', '7'

Whole numbers: int

Use int for quantities that naturally have no fraction:

int completedLessons { 5 };
int remainingDays { 360 };
int score { 0 };

The values can be positive, negative, or zero. A whole-number count, age, attempt number, or menu choice will often use int.

Decimal measurements: double

Use double when fractional values matter:

double temperatureCelsius { 21.5 };
double breakMinutes { 5.5 };
double price { 19.99 };

For ordinary decimal values, prefer double rather than float. A float exists and uses less precision:

float smallMeasurement { 1.5F };

Notice the F suffix. Without it, a decimal literal such as 1.5 is normally a double. At this stage, use double whenever your value might reasonably need a decimal part.

Yes-or-no values: bool

A bool holds exactly one of two values:

bool isRunning { true };
bool hasFinished { false };

The words must be lowercase: true and false.

Booleans will become especially useful when you learn if statements and loops. For now, recognize them as variables that answer a yes-or-no question.

One character: char

A char stores one character enclosed in single quotes:

char sessionCode { 'A' };
char command { 'q' };
char grade { 'B' };

The quotation marks matter:

char letter { 'A' };       // one character
"A"                        // text, not a char

Similarly, '7' is the character seven, whereas 7 is the integer seven. They may look related to a person, but C++ treats them as different kinds of values.

We will work with full text—such as names and sentences—later using std::string. For now, use char only when one individual character is the right data model.


Declaring, initializing, and naming variables

There are three related actions to distinguish.

1. Declare and initialize in one statement

This is the normal approach:

int dailyTarget { 30 };

The variable is created and immediately receives a known value.

2. Declare first, assign later

Sometimes the value is not known when the variable is created:

int dailyTarget;
dailyTarget = 30;

The second line is an assignment. It puts 30 into the already-existing variable.

However, do not display or otherwise use dailyTarget between those two lines. A local variable declared without an initial value can contain an unpredictable value. Reading it before assigning a meaningful value is a serious program error.

If zero is a sensible starting value, initialize it explicitly:

int completedLessons {};

For an int, empty braces initialize the value to 0. This is better than leaving the variable uninitialized.

3. Update an existing variable

Once a variable exists, do not write its type again when changing it:

int dailyTarget { 30 };

dailyTarget = 45;

After the second statement, dailyTarget holds 45. The earlier 30 has been replaced.

The assignment symbol = means “evaluate the right side and store its value in the variable on the left.” It does not mean that both sides are permanently equal in the mathematical sense.

For example:

int completedLessons { 1 };

completedLessons = completedLessons + 1;

The program takes the current value, adds one, and stores the result back in the same variable. Afterward, completedLessons holds 2.

Later, you will learn shorthand such as completedLessons += 1;. For now, the longer form makes the update process clear.

Give variables useful names

A good variable name describes the value’s purpose:

int studyMinutes { 30 };
double temperatureCelsius { 21.5 };
bool isComplete { false };

Use lower camel case in this course: start with a lowercase letter, then capitalize each later word.

int totalScore { 0 };
int numberOfAttempts { 3 };
double averageTemperature { 18.2 };

Follow these basic rules:

  • Start names with a letter.
  • After that, use letters, digits, and underscores.
  • Do not include spaces or hyphens.
  • Do not start a name with a digit.
  • Do not use C++ keywords such as int or double as names.
  • Treat uppercase and lowercase letters as different: score and Score are different names, though using such similar names is confusing.
  • Declare one variable per line while learning. It is easier to read and avoids initialization mistakes.

These are invalid names:

int study minutes { 30 };  // spaces are not allowed
int 2ndLesson { 2 };       // cannot start with a digit
int study-minutes { 30 };  // hyphen is not part of a name

Brace initialization protects against lost information

Brace initialization can catch an important mismatch: trying to put a decimal value into an integer variable.

int wholeMinutes { 30.5 };

Do not add that line to a working program. Visual Studio should issue a compiler diagnostic because 30.5 cannot be represented exactly by an int; the .5 would be lost.

That safeguard is one reason to prefer braces.

By contrast, an assignment after creation may permit the conversion:

int wholeMinutes { 30 };

wholeMinutes = 30.5;

The resulting value is 30, because the decimal part is discarded. Visual Studio may also warn you about this conversion, but the important habit is simpler: use int for whole values and double for values that may have fractions.

The same general principle applies to the other types:

bool readyToStudy { true };
char sessionCode { 'A' };
double breakMinutes { 5.5 };

Choose a type that matches both the current value and what the value is meant to represent.


Build: a study-session tracker

Create a small program that records fixed details about a study session, then changes two of them. This deliberately uses hard-coded values because you have not yet learned console input.

Replace your existing .cpp file contents with this:

#include <iostream>

int main()
{
    int studyMinutes { 30 };
    double breakMinutes { 5.5 };
    int completedLessons { 1 };
    bool isFirstSession { true };
    char sessionCode { 'A' };

    std::cout << "Study minutes: " << studyMinutes << '\n';
    std::cout << "Break minutes: " << breakMinutes << '\n';
    std::cout << "Session code: " << sessionCode << '\n';
    std::cout << "First session flag: " << isFirstSession << '\n';

    studyMinutes = 40;
    completedLessons = completedLessons + 1;

    std::cout << "Next study target: " << studyMinutes << '\n';
    std::cout << "Completed lessons: " << completedLessons << '\n';

    return 0;
}

Save with Ctrl+S, then run without debugging using Ctrl+F5.

The output should be similar to this:

Study minutes: 30
Break minutes: 5.5
Session code: A
First session flag: 1
Next study target: 40
Completed lessons: 2

The bool value true appears as 1 with the default std::cout formatting. false would appear as 0. That is normal; later, you will learn ways to make Boolean output more reader-friendly when necessary.

Trace the program in order:

  1. Each variable is created and receives its initial value.
  2. The first four output statements display those initial values.
  3. studyMinutes = 40; overwrites the previous 30.
  4. completedLessons = completedLessons + 1; updates 1 to 2.
  5. The final two output statements display the new values.

Make a few purposeful edits, rebuilding after each one:

  • Set studyMinutes to your actual intended daily target.
  • Change sessionCode to another single character, such as 'B'.
  • Change isFirstSession to false and observe the output.
  • Change breakMinutes to a value with a decimal part, such as 10.25.
  • Predict the value that will appear if you change the update to completedLessons = completedLessons + 3;, then run the program to verify it.

Remember the output distinction from the previous lesson:

std::cout << studyMinutes << '\n';    // displays the value, such as 30
std::cout << "studyMinutes\n";        // displays the letters studyMinutes

The first line uses the variable; the second uses a text literal.


Common variable mistakes

MistakeExampleRepair
Using a variable before initializing itint score; std::cout << score;Initialize it, such as int score { 0 };.
Repeating the type when updatingint score { 0 }; int score = 1;Use score = 1; after the first declaration.
Trying to store a decimal in an intint distance { 3.5 };Use double distance { 3.5 }; if the fraction matters.
Using double quotes for a charchar grade { "A" };Use single quotes: char grade { 'A' };.
Printing a variable name as textstd::cout << "score";Remove quotes to output its value: std::cout << score;.
Using = as though it tests equalityscore = 10Here it assigns 10. You will learn == for comparisons in a later module.

A reliable debugging question is: Does the type match the meaning and form of the value? If you see a decimal, think double. If you see exactly true or false, think bool. If you have one quoted symbol, think char; if you have a whole-number quantity, think int.


Key takeaways

  • A variable has a type, a name, and usually an initial value.
  • Use int for whole numbers, double for ordinary decimal values, bool for true or false, and char for one character in single quotes.
  • Prefer brace initialization, such as int score { 0 };, because it makes initialization clear and rejects certain unsafe conversions.
  • An assignment such as score = 10; replaces the variable’s current value. Do not repeat the type when updating an existing variable.
  • Initialize local variables before using them.
  • Use descriptive lower-camel-case names such as studyMinutes and completedLessons.
  • Write a variable name without quotes to output its stored value through std::cout.

Next, you will replace hard-coded values with information typed by the user using std::cin.

Can't find a good explanation? Sign up and we'll make it for you

Sign up