Search⌘ K
AI Features

Remember Values

Explore how to create and use variables in C++ to store values like numbers and characters. Learn to declare variables, understand key data types, and update stored information in your programs.

You now know how to print to the screen and perform basic math with C++. Now, let’s give your program a memory. In this lesson, you’ll learn how to create variables, containers for numbers, letters, or anything your program needs to remember.

Goal

You’ll aim to:

  • Declare variables using C++ types.

  • Store and reuse values.

  • Understand type basics: int, double, char.

Make a variable

To declare a variable in C++, we use the following simple syntax:

Variable declaration in C++
Variable declaration in C++

Now, let’s use this syntax in the code below to declare and use a variable of integer (int) data type:

C++
#include <iostream>
using namespace std;
int main() {
int score = 100; // Stores 100 in 'score'
cout << "Score: " << score << endl; // Prints the value of score (100) with label (Score: )
return 0;
}

Here is a visual representation of our variable, score:

Breakdown of a variable declaration in C++
Breakdown of a variable declaration in C++

More types

Here are some additional data types we can use for our variables, depending on the type of value they will hold:

C++
#include <iostream>
using namespace std;
int main() {
double price = 4.99; // Decimal number
char grade = 'A'; // Single character
cout << "Price: $" << price << endl;
cout << "Grade: " << grade << endl;
return 0;
}

You’ve used three core types.

int, double, and char
int, double, and char

Store the result in a variable

We have already done some math with C++. Now, let’s store the result of our calculation in a variable:

C++
#include <iostream>
using namespace std;
int main() {
int total = 8 + 12; // Creates an integer variable named total and stores the result of 8 + 12 in it
cout << "Total: " << total << endl; // Prints the text "Total: " followed by the value of total, then moves to a new line
return 0;
}

Now your math lives inside a named value.

Change a variable

We don’t just declare a variable and use it unchanged throughout our program; the value a variable holds can be changed or updated (hence the name ‘variable’):

C++
#include <iostream>
using namespace std;
int main() {
int age = 18; // Stores 18 in age
age = age + 1; // Increases age by 1
cout << "Next year: " << age << endl; // Prints updated age with label
return 0;
}
Updating a variable in C++
Updating a variable in C++

You have updated and reused a variable.

Quick type reference

  • int → Whole numbers

  • double → Decimals/floating point

  • char → Single letters or characters