Variables in C++
Learn why we need variables in our code and how we can use them.
We'll cover the following...
Up until now, we have displayed a pre-decided text—“Hello, World!”—on the screen. No matter how many times we run the program, the same text will be displayed.
In programming, hard coding refers to the practice of embedding specific values or data directly into the code instead of allowing them to be determined at runtime by getting them as user input or extracting them from external files.
Variable in memory locations
What if we wanted to print a different text each time? What if we wanted the user to decide what needs to be displayed? Suppose we need to write a program that displays the user’s age. To make this possible, the programming language needs to provide us with a feature using which we can take the input from the user, save it to a memory location, and retrieve it from the memory location whenever the program requires it. Have a look at the following slides:
Suppose we want to write a program that displays the circumference of a circle. Let’s recall the formula for calculating the circumference of a circle:
In this equation, which information remains the same (can be hardcoded), and which information changes for each circle (needs to be stored in a variable)?
The feature we need is called variables. Let’s dive in!
Variables—the building blocks of our program
A variable is a named memory location that holds data during program execution. Think of it as a labeled container that you can use to store and manage information throughout your code.
Variables are located in the minds of programmers and in the memory of computers. Programmers use symbolic names to describe variables in their minds. For example, in our example given above, the radius of a circle would exist in the programmer's mind and their code as “radius” and would be referred to with that name. However, in the computer’s memory, it would occupy a space that would be referred to by the address of that memory region, which would be a numeric value.
Identify the variables in the given sentence:
“I bought an animal, it was a duck and named it Daffy.”
Note: The compiler assists programmers by managing the relationship between the symbolic and numeric representations of the locations of variables to reduce the number of errors that programmers would surely make if there were required to refer to every variable they have in mind purely by its current location in the memories of their computers.
Using variables in your code
Let’s have a look at how we can create (also referred to as “declare”) a variable, assign an initial value, and then display its value on the screen. Variables can store different types of values, for example, integers, floating point numbers, characters, and strings etc. For this lesson, we’ll only work with variables that can hold integer values and leave the other types for a later lesson.
Declaring variables
Declaring variables is easy. You specify its type, give it a name, and end the line of code with a semicolon.
<variable_type> <variable_name> <;>
Let’s look at an actual example.
int age;
In the above code, we create a variable named age
of the type integer. This means that only an integer value can be stored at the memory location that is being referred to by the variable name age
.
Assigning values
What are the variables without values? In order to use a variable, you just need to declare it first and give it a value. To assign a value to a variable, you simply write its name, followed by the assignment operator (which is simply the “equals to” sign from our math books), followed by the actual value being assigned, before ending the line of code with a semicolon.
<variable_name> <=> <value> <;>
Let’s see what it looks like in practice.
int age;age = 18;
In the above code, we first create a variable named age
of the type integer. In the next line, we assign the value 18
to it.
You might be wondering, can’t we cover both steps in a single line of code? Yes, C++ allows that. The following code snippet does that:
int age = 18;
Using a variable without first declaring it is a common mistake beginner programmers make. Some languages, like Python, are kinder towards beginners and allow that. C++, on the other hand, displays an error message and won’t compile the program if a variable has been used without being declared first.
It is a good practice to initialize a variable to zero when declaring it. Initialization means assigning a value at the time of declaration. This helps us avoid many bugs. Beginner programmers often make the mistake where they declare a variable and then use it in their code without assigning a value. This could lead to unpredictable behavior. The compiler might automatically assign a zero to the variable, or the variable might contain a garbage value, or in case the memory location was previously used for another variable, it might still hold that value.
A question comes to mind: how can we declare multiple variables in a single program? There are two ways to do this:
First—a more verbose option—we can declare each variable on a separate line as shown in the following code snippet:
int age = 18;int year = 1998;
Second—for some a cleaner version—if the variables are of the same type, we can declare each variable in the same line as shown in the following code snippet. You would start by specifying the variable type, followed by a comma-separated list of each variable’s name (and assignment if needed), followed by a semicolon at the end.
<variable_type> <variable1_name> <,> <variable2_name> <,> <variable3_name> <;>
Let’s look at an actual example here:
int age = 18, year = 1998, month = 12;
It is a good practice to define each variable on a separate line, followed by a comment that describes its purpose in the program.
You can also assign a value to a variable using another variable that holds the required value. The data inside a variable can be assigned to another variable. Let’s consider an example where we want to assign the value of the variable a
to the variable b
. Look at the slides given below to visualize the process of the declaration of variables making changes in the state of memory:
Displaying the stored values
Once the values have been assigned, we can display the value stored in the variable using a simple cout
statement. The following code does that:
#include <iostream>using namespace std;int main() {int age = 18, month = 12;cout << age;cout << month;return 0;}
Use of endl
When you run the code, you will notice that the output is quite confusing. There is no space between the age and month values. Let’s fix that, try again by running the following code with an additional line of code:
#include <iostream>using namespace std;int main() {int age = 18, month = 12;cout << age;cout << endl;cout << month;return 0;}
Notice the endl
. This moves the cursor to the beginning of the next line, effectively printing any subsequent output on a new line. Try it in the above playground and see the output.
Display multiple values with cout
Alright! The output has been fixed. But the code is lengthy and not too elegant. Can these lines of code be combined into one? Yes, C++ allows that. Let’s have a look.
#include <iostream>using namespace std;int main() {int age = 18, month = 12;cout << age << " " << month << endl;return 0;}
In the above playground, you’ll notice two new points. First, if we want to display multiple values, we can do that by writing cout
only once, followed by <<
and the variable name, before finally ending the line of code with a semicolon.
<cout> << <variable1> << <variable2> << <variable3> <;>
Second, we can add a single whitespace character using a space wrapped between double quotes “ ”
. You can also try to display age
and month
using the same cout
statement on two separate lines. Please use the playground provided above. If you are still not sure, take a look at the hint to perform the task.
Rules for naming variables and best practices
C++ is a case-sensitive language, all variables must have unique names. The unique names are also known as identifiers that point to a specific location in memory. The identifiers must be meaningful and depict the role of the variable in the code. The variable name can have letters (a
,b
, c
), numbers (1
, 2
, 3
) and underscores (_
). The variable names cannot have whitespaces or special characters like +
, -
, *
, !
, #
, %
, etc. Look at an example below of how the case works in C++ naming:
int bodyTemp, bodytemp, BODYtemp;
In the code above, all the variables are different and thus point to different locations in memory. There is a convention that all variables must start with a letter or an underscore. There are some reserved words in C++ for defining data types like int
, string
, include
, class
, etc. These words can not be used as a variable.
It is often recommended that variables show the role they are playing and should have a specific length. For example, when creating a variable showing a user's account balance, here are some variable names that the user can use or must avoid. The reasons are mentioned in the comments that follow each declaration.
int acc_bal; // This is short and clear but not everyone might know what acc and bal stand forint usersaccountbalance; // This variable name length is very long and is difficult to readint userbal; // This variable name is harder to read—splitting with an underscore would helpint xyz; // This variable name doesn't make senseint accountBalance; // This variable name is meaningful and also readable due to the camel case
A basic rule for defining a variable is to use underscores or camel case variables to increase readability and associating meaning with the variables.
Note: Some compilers might impose a limit on the variable name’s length so you should try to limit the variable length to 31 or fewer characters. This also makes the code easy to read.
Test you understanding
To test your comprehension of the concepts discussed in this lesson, answer the questions given below:
(Select all that apply.) Identify the error in the following code:
init test = p;
cout << Test << " ";
init
is not a data type.
p
is not defined.
cout
cannot print two things at once.
test
and Test
are different.