Creating Variables

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

Free, Unlimited Access
3D art showing a fantasy RPG character
Ryan McCombe
Ryan McCombe
Updated

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
boolisAliveIs the monster currently alive?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.

Let's start with the bool that represents whether or not the monster is currently alive:

bool isAlive;

This line is an instruction that we want to create a variable of type bool, and we will be using the name isAlive to identify it. Remember, and instruction like this is 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 isAlive identifier any time we want to access the data stored in that memory location.

Test your Knowledge

Creating Variables

How can we create an integer variable called Health?

Code Comments

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

// Is the monster currently alive?
bool isAlive;

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 isAlive; // This is a comment

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

bool isAlive; /* This is a comment */

This style of comment can span multiple lines:

/*
This is a comment
on multiple lines
*/
bool isAlive;

It can even go in the middle of a line of functional code, although this is not commonly used:

bool /* This is a comment */ isAlive;

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 code too, especially as a beginner. They can help you get back up to speed 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 alive?
bool isAlive;
isAlive = false;

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

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 isAlive; will create a variable, but isAlive 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, isAlive, IsAlive, and isalive are all different names. If we want to access a variable we previously created, we need to use the 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 initializing the variable. This code will request some space to store a boolean, and initialize that boolean to contain the value of false:

// Is the monster currently alive?
bool isAlive { 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 initializing a variable with a value, we can also do it with the = symbol

// Is the monster currently alive?
bool isAlive = false;

The Many Ways to Initialise C++ Variables

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

Copy initialization uses the = operator:

bool isAlive = false;

Uniform initialization uses the {} syntax:

bool isAlive { 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 initialization 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 initialization using { and } was a later addition to the language and solved many of those issues. It is the modern, recommended approach, so it's what we'll prefer.

Let's 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

Initializing Floats

How might we initialize 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!";
}
Hello World!

Let's 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. The 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 << "\nand its level is " << Level;
}

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.

Troubleshooting: Redefinition of Variable

One of the most common errors we will make with variables is repeating the type when trying to update a variable that was already created.

This error will generally be reported in our IDE using wording like 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 isAlive;

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

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

bool isAlive;

isAlive = false;

Troubleshooting: Expected ; after expression

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

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

bool isAlive { false };

// Error! This brace syntax is only for initialization
isAlive { true };

We should use = to update a variable

bool isAlive { false };

isAlive = 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 };
3
4// We can also initialize a variable using =
5int ExperienceLevel = 1;
6
7/*
8We can update the value of an existing
9variable later in our code using the = sign
10*/
11Health = 200;
12
13// We can copy booleans too
14bool isAlive { false };
15bool canAttack { isAlive };
16
17/*
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 initialized
23*/
24int Health = 250; // error!
25
26/*
27However, when updating a variable, we cannot
28use the { braces } syntax.  Braces are only
29used for initialization.  Therefore,
30line 32 will cause an error
31*/
32ExperienceLevel { 3 }; // error!

Line Numbers

The previous code snippet shows 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 simply give us an easy way to communicate which parts of our code we’re talking about.

For this reason, they’re commonly enabled in our IDEs by default.

Summary

In this lesson, we've covered several key aspects of creating and updating variables in C++. Here's a quick recap:

  • Variable Creation: We learned how to declare variables in C++ using various data types like bool, int, float, and string.
  • Understanding Statements: We explored the concept of a statement in C++, focusing on its structure and the necessity of ending each statement with a semicolon.
  • Memory Allocation: Discussed how declaring a variable requests memory space and how the variable name/identifier allows us to re-access this memory later.
  • Using Comments: We introduced how to use comments (// and /* ... */) to make code more readable and understandable.
  • Initializing Variables: The lesson covered initializing variables with values using = and braces {}.
  • Error Handling: We delved into common errors such as 'Use of undeclared identifier' and 'Redefinition of variable', and how to avoid them.
  • Outputting Variables: Demonstrated how to output variable values to the console using cout.
  • Copying Variables: Explored initializing variables using the value of other variables, and how they can be updated individually.

Preview of Next Lesson

In our next lesson, we will shift our focus to Using Numeric Variables in C++. This upcoming lesson will delve into:

  • Different Numeric Types: Understanding the variety of numeric data types in C++, like int, float, double, and their usage.
  • Arithmetic Operations: We will learn how to perform basic arithmetic operations with numeric variables.
  • Numeric Precision and Limits: Exploring the concepts of precision in floating-point numbers and the limits of different numeric types.

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

Was this lesson useful?

Next Lesson

Numbers and Literals

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
Ryan McCombe
Ryan McCombe
Updated
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
Types and Variables
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:

  • 56 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Next Lesson

Numbers and Literals

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 © 2024 - All Rights Reserved