Creating Variables in C++

Creating variables to store and update the data that describes our objects. We also introduce comments, allowing us to describe our code in plain language.
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

3D art showing a fantasy RPG character
Ryan McCombe
Ryan McCombe

In the previous lesson, we constructed a list like this, to show some of the data we would need to describe one of our monsters:

Data TypeVariable NameDescriptionExample
boolisDeadIs the monster currently dead?false
intHealthHow much health the monster has remaining150
floatArmorHow much damage resistance the monster has0.2
stringNameThe monster's name"Goblin Warrior"

In this lesson, we will see how we can create the variables to store this data.

Lets start with the bool that represents whether or not the monster is currently dead:

bool isDead;

This line is an instruction that we want to create a variable of type bool, and we will be using the name isDead to identify it. An instruction like this is sometimes called a statement and, in C++, we end each statement with a semicolon ;

This statement will cause our program to make a request to the operating system, asking that we be allocated some space in memory. Specifically, it is requesting enough memory to store a boolean value.

From then on, we can use the isDead identifier any time we want to access the data stored in that memory location.

Test your Knowledge

How can we create an integer variable called Health?

Comments in C++

By using // in our code, we can add a comment.

// Is the monster currently dead?
bool isDead;

Comments are mainly to help developers describe in plain language what their code is doing, and why. They are ignored by the processes that convert our code into an executable.

Anything after the // on a line of code is treated as a comment. In the above example, the entire line is a comment. But comments can also be on the same line as functional code:

bool isDead; // This is a comment

As an alternative to a line comment using //, we can also place comments between /* and */ tokens:

bool isDead; /* This is a comment */

This style of comment can go in the middle of a line:

bool /* This is a comment */ isDead;

And it can also span multiple lines:

This is a comment
on multiple lines
bool isDead;

We'll use comments quite a lot in the code samples of this lesson to explain what is happening.

It is often worth adding comments to your own code too, especially as a beginner. They can help you understand what is happening if you come back to your code later, and need a reminder of what certain lines are doing.

Variable Values

Once we have created a variable, we can store a value in it like this:

// Is the monster currently dead?
bool isDead;
isDead = false;

The isDead = false; statement visits the memory location created for the isDead variable. It then updates that location to represent the boolean value false.

C++ Error: Use of undeclared identifier

This error occurs when you're trying to access a variable, and C++ doesn't know what that variable is. There are two common causes for this error:

We're trying to create a variable, but did not include the type

To create a variable, we need to specify the type. bool isDead; will create a variable, but isDead will try to access a variable that was already created.

The variable name is not correct.

Like most programming languages C++, is case sensitive. Capitalisation matters.

For example, isDead, IsDead and isdead are all different names. If we want to access a variable we previously created, we need to use the exact same name we used when we created it.

We can provide an initial value for a variable at the same time we first declare it. This is called initialising the variable. This code will request some space to store a boolean, and initialise that boolean to contain the value of false:

// Is the monster currently dead?
bool isDead { false };

The { and } characters are commonly called braces and are used a lot in programming. On US/UK keyboard layouts, they are typically to the right of the P key.

When initialising a variable with a value, we can also do it with the = symbol

// Is the monster currently dead?
bool isDead = false;

The Many Ways to Initialise C++ Variables

We've already seen two different ways to initialise variables in C++

Copy initialisation uses the = operator:

bool isDead = false;

Uniform initialisation uses the {} syntax:

bool isDead { false };

There are even more ways, but these two are the most common. = was historically used, and is generally going to be the most familiar to people coming from other programming languages.

However, copy initialisation using = has some problems. We will point out those problems in later chapters, when we're exploring areas where they're likely to crop up.

Uniform initialisation using { and } was a later addition to the language, and solves many of those issues. It is the modern, recommended approach, so it's what we'll prefer.

Lets also create an int and a string variable:

int Level { 5 };

// Remember, strings need wrapped in double quotes
string Name { "Goblin Warrior" };

Test your Knowledge

How might we initialise a floating point variable called Armor?

Outputting Variables

In the first lesson, we were working with this basic code structure to stream information to the console.

#include <iostream>
using namespace std;

int main()
  cout << "Hello World!";

Lets see how our variables integrate with this. Until we learn more, I'd suggest creating all our variables after the using namespace std; line, and doing all cout statements between the { and the } of the main code block.

Code Highlighting

Within the code samples we show, we will sometimes highlight specific lines of code. Lines we want to draw your attention to are highlighted in green:

int LookAtMe { 5 };

Lines that contain an error are highlighted in red:

int ThisWontWork { "Hello World!" };

Sometimes, a line of code will technically work, but isn't something we should do. We'll highlight those lines in orange:

int DontDoThis { true };

The following is an example of a program using our new knowledge of variables:

#include <iostream>
using namespace std;

string Name { "Goblin Warrior" };
int Level { 10 };

int main()
  cout << "The monster's name is "<< Name;
  cout << " and its level is " << Level << endl;

When we compile and run this, we should see a message like this logged out to the terminal:

The monster's name is Goblin Warrior and its level is 10

Note, if we try to cout boolean values, you might not get what you expect. true will log out as 1 and false will log out as 0. That's not very useful right now, but we will explore booleans in more detail soon.

C++ Error: Redefinition of Variable

The most common error beginners will make with variables is repeating the type when trying to update a variable that was already created.

This error will generally be reported as "redefinition of (your variable name)"

We only need to set the type of the variable when we first create it.

The following would be invalid code, as it is attempting to create two different variables, using the same name:

bool isDead;

// Error!  We already have a variable called "isDead"
bool isDead = false;

When we want to access or update a variable we already created, we just use the name, not the type:

bool isDead;

isDead = false;

C++ Error: Expected ; after expression

Another common error is misuse of the brace syntax. We only use { and } to initialise a variable, not to update it.

Therefore, the following example would also generate an error, which will generally be reported as "Expected ; after expression":

bool isDead { false };

// Error! This brace syntax is only for initialisation
isDead { true };

We should use = to update a variable

bool isDead { false };

isDead = true;

Copying Variables

We can initialize a variable using the value of another variable.

In the below code, we are copying the value of the MaxHealth variable into a new variable called CurrentHealth.

int MaxHealth { 150 };
int CurrentHealth { MaxHealth };

After this code runs, we will have two variables that initially have the same value, but can then be updated individually.

More Examples

The code sample below shows more examples of how we can create and work with variables.

1// Initialise a new integer variable
2int Health { 150 };
4// We can also initialize a variable using =
5int ExperienceLevel = 1;
8We can update the value of an existing
9variable later in our code using the = sign
11Health = 200;
13// We can copy booleans too
14bool isDead { true };
15bool canBeLooted { isDead };
18Remember, we don't redeclare the variable's
19type when we update its value.  We only
20declare its type when we first create it.
21Line 24 is an error because Health
22was already initialised
24int Health = 250; // error!
27However, when updating a variable, we cannot
28use the { braces } syntax.  Braces are only
29used for for initialisation.  Therefore,
30line 32 will cause an error
32ExperienceLevel { 3 }; // error!

Line Numbers

The previous code snippit is the first one in this course to show line numbers to the left. In the above example, the line numbers go from 1 to 32.

Line numbers are not part of the language, and should not be included in our code. They are simply a way to let humans refer to specific parts of the code. For example, "there is an error on line 24".

Let's continue our initial exploration of variables by looking at numbers in a bit more depth!

Was this lesson useful?

Ryan McCombe
Ryan McCombe
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

C++ Fundamentals
3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access!

This course includes:

  • 66 Lessons
  • Over 200 Quiz Questions
  • Capstone Project
  • Regularly Updated
  • Help and FAQ
Next Lesson

Numbers in C++

An introduction to the different types of numbers in C++, and how we can do basic math operations on them.
3D art of a boy using an abacus
Contact|Privacy Policy|Terms of Use
Copyright © 2023 - All Rights Reserved