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.

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, an 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 updates our isAlive variable to have the value of false.

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 the operating system give us enough space in the system's memory 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;

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.

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.

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 = operator
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!

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 introduced 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.
Next Lesson
Lesson 4 of 60

Numbers

An introduction to the different types of numbers in C++, and how we can do basic math operations on them.

Have a question about this lesson?
Answers are generated by AI models and may not have been reviewed for accuracy