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.
{"type":"image","url":"https://d8it4huxumps7.cloudfront.net/bites/wp-content/banners/2024/9/66f2831eec417_what_are_variables_in_c.jpg?d=700x400","caption":"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.","isV2":true,"blockId":"d03578f0-ae5a-478b-951c-142f1a176268","lessonId":"9da9879a-eafc-4380-b588-77f10e3314a3"}
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:
| Part | Meaning |
|---|---|
int | The variable holds whole numbers. |
studyMinutes | The 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.
{"type":"video","title":"Learn C++ With Me #3 - Data Types and Variables","learning_duration":765,"video_id":"zgutFVxOlTY","par_intro":"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.","par_directions":"Watch <span data-type=\"resource_video_timerange\" data-resource-subitem-id=\"c347211b\" data-range-start=\"119\" data-range-end=\"282\">numeric and Boolean types</span> for `int`, decimal types, and `bool`. Then skip to <span data-type=\"resource_video_timerange\" data-resource-subitem-id=\"5907fcf4\" data-range-start=\"326\" data-range-end=\"370\">the char distinction</span> for the difference between a character in single quotes and text in double quotes.\n\nNext, watch <span data-type=\"resource_video_timerange\" data-resource-subitem-id=\"beb65277\" data-range-start=\"587\" data-range-end=\"654\">a declaration</span>, where a typed variable is created and printed. Continue through <span data-type=\"resource_video_timerange\" data-resource-subitem-id=\"fb926a58\" data-range-start=\"654\" data-range-end=\"752\">type mismatch</span> to see why storing a decimal in an integer can lose information. Finish with <span data-type=\"resource_video_timerange\" data-resource-subitem-id=\"a79a937d\" data-range-start=\"784\" data-range-end=\"969\">naming rules</span> and <span data-type=\"resource_video_timerange\" data-resource-subitem-id=\"9070fd64\" data-range-start=\"969\" data-range-end=\"1177\">updates and copies</span>. Notice that the type appears when the variable is created, but not when its value is changed later.","video_duration":1197,"isV2":true,"blockId":"0d3796db-b9c2-463f-b44b-744c0128d4c8","lessonId":"9da9879a-eafc-4380-b588-77f10e3314a3"}
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.
| Type | Stores | Examples |
|---|---|---|
int | Whole numbers | 0, 27, -4 |
double | Decimal numbers, with high precision | 18.5, -2.75 |
float | Decimal numbers, with less precision than double | 18.5F |
bool | A logical value | true, false |
char | One 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.
{
"type": "exercise",
"id": "183011d3-f758-419f-bba5-acc63de51144"
}
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
intordoubleas names. - Treat uppercase and lowercase letters as different:
scoreandScoreare 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.
{
"type": "exercise",
"id": "fc6bc028-3bcf-476b-8095-b65f839e0474"
}
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:
- Each variable is created and receives its initial value.
- The first four output statements display those initial values.
studyMinutes = 40;overwrites the previous30.completedLessons = completedLessons + 1;updates1to2.- The final two output statements display the new values.
Make a few purposeful edits, rebuilding after each one:
- Set
studyMinutesto your actual intended daily target. - Change
sessionCodeto another single character, such as'B'. - Change
isFirstSessiontofalseand observe the output. - Change
breakMinutesto a value with a decimal part, such as10.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.
{
"type": "exercise",
"id": "1c0c4b2e-7485-4ac2-82f5-f7646281f95c"
}
Common variable mistakes
| Mistake | Example | Repair |
|---|---|---|
| Using a variable before initializing it | int score; std::cout << score; | Initialize it, such as int score { 0 };. |
| Repeating the type when updating | int score { 0 }; int score = 1; | Use score = 1; after the first declaration. |
Trying to store a decimal in an int | int distance { 3.5 }; | Use double distance { 3.5 }; if the fraction matters. |
Using double quotes for a char | char grade { "A" }; | Use single quotes: char grade { 'A' };. |
| Printing a variable name as text | std::cout << "score"; | Remove quotes to output its value: std::cout << score;. |
Using = as though it tests equality | score = 10 | Here 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
intfor whole numbers,doublefor ordinary decimal values,boolfortrueorfalse, andcharfor 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
studyMinutesandcompletedLessons. - 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