Please share...

  • Video courses

    All game programming videos just $19 - For a very limited time these three videos and thousands more are up to 90% off!

    Just enter coupon code NEWU19 in cart/checkout

The Unreal Engine Developer Course – Learn C++ & Make Games

Learn and Understand C++

Over 260 video lectures in 44 hours of video!

Learn C++: Beginner to Advanced

Join thousands of successful students!

Whenever we code a PC game, we need to ‘know’ what the situation in the game is at any given point in time. As an example, things like the player’s score, how many people connected to  game-lobbies, where in the game level all the players and NPCs are and of course what they are doing. The game’s variables are the part of our code that allows us to do this. Variables are essentially our game’s data.

About this tutorial

Skill level 1
Time to read: 10 minutes

New Concepts:

  1. C++ variables
  2. Declaration
  3. Initialization

Recommended preparation tutorials

Projects related to or that demonstrate these concepts

  • None

All of these variables are part of the data of the game. And it is very easy to think of lots more examples of data, a typical game might need. What about the images for the graphics, what if each object has a different image for each of many frames of animation? What about data to describe the game environment, artificial intelligence or the layout of the different levels of a game? All this information, even in a simple platform game for example, will become fairly complicated once the whole game is built.

C++ begins to solve this problem with variables. Variables enable us to easily store data in a memorable/meaningful and flexible way. We mentioned a moment ago that we would need to remember the player’s score. To manage this particular piece of data we can create a variable in our code and we can make it memorable by giving this variable an appropriate name. Let’s call our variable to hold the player’s score-  playerScore.

Variable naming conventions

  • Beginning C++ Game Programming

    Beginning C++ Game Programming

    This book is all about offering you a very fast and fun introduction to the world of game programming and C++. It will begin by teaching you the programming basics such as variables, loops, and conditions. In this book there is very little theorizing. If you want a deep discussion of all the ins and outs of C++ concepts look elsewhere. If you are starting from a knowledge of zero C++ and want to build great games- fast, take a look at this book.
    • Setup a C++/SFML/Visual Studio development environment
    • Build a fast, fun Timber clone after learning basic C++
    • Discover the fundamentals of C++ object oriented programming and build a multi-level, top-down 2D, scrolling zombie survival/shooter
    • Explore some advanced C++ concepts and make a side scrolling, co-op split-screen multiplayer platform game with directional sound, particle effects and your very own level designs!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    C++ for Game programmers book

    C++ For Game Programmers

    Already know the basics of C++ but want to dig much deeper in an entirely game-focussed context? C++ for Game Programmers is that book. This best selling title supplements your knowledge by putting everything into perspective from a game-development point of view. The book points out the most effective C++ practices and steers you away from the potentially dangerous ones. It describes common C++ techniques to solve specific problems most game developers face.
    • From a gaming perspective, learn about inheritance, performance, memory management, and STL to object creation, object serialization, and scripting languages
    • Explore C++ Design Patterns and high-level problem-solving constructs that are most commonly found in games
    • Discover custom Structures and algorithms, which provides a detailed hands-on discussion of using C++ to create efficient solutions to difficult problems in a highly structured manner
    Amazon USA
    Amazon UK
    Amazon CA
    Game Programming Patterns book

    Game Programming Patterns

    If you are serious about writing high quality, reusable, efficient code using C++ or indeed any other language, then inevitably you will need to seriously hone your knowledge of game programming patterns. If you don't know what game programming patterns are they are simply the solutions to design problems. If you have programmed even a basic game you will have noticed that the code gets long and hard to manage, very quickly. The more features you add the more sprawling and messy your code gets. In addition to usability/reuse-ability, our game code needs to be efficient enough for the game to run smoothly. That's what this book will do for you.
    • Learn to write a robust game loop, how to organize your entities using components, and take advantage of the CPUs cache to improve your performance
    • Discover how to organize your entities using components, and take advantage of the CPUs cache to improve your performance.
    • Never again wonder what is the "best" way to organize your game code
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)

You might have noticed that the name is simply a truncation of the two words, with the first letter of the first word in lower case and the second letter of the second word in upper case. In C++ we can call our variables almost anything we want but by using meaningful names there is never any doubt about what the variable is for. Furthermore, by using the combination of lower and upper case letters we are adopting a naming convention. By sticking to a naming convention especially when our code gets more complicated, it will make it more easily readable and less likely for mistakes to occur.

Here we are using the simple lower case word followed by upper case word because it makes the second word clear and when we introduce more types of C++ code later in the course it will make our variables stand out from other types of code.

C++ variable types

Before we can begin to write code with variables we must choose what type of variable each will be. Types are simple to understand. It is just a case of thinking about what information (what type) any particular variable will be used to store. In the case of our playerScore variable, we are storing a number, a score. But let’s consider some other potential variable types.

What about the name of the player, perhaps we could use a variable called playerName. Here we don’t want to store a number but a collection of letters from the alphabet that form the player’s name. Think perhaps also about data that stores if something has occurred- or not, that is true or false. This is much more common than it might first seem and some examples soon will help. Also consider we might need to use different types of number, just like in the real world. Whole numbers, fractions etc.

To avoid any ambiguity about what type a variable is, C++ makes us declare a type before we can use a variable. This makes it plain what that variable will be used to store. The C++ compiler then knows how to deal with our variable.

Let’s have a look at some common types in C++. The list below is only a few of the available types in C++; all the variable types should appear fairly straight forward with the exception of one really powerful variable type, known simply as an object or class, which will be covered in a later tutorial. Note also that the different ways in which we can handle these variables will also be discussed in a more advanced variables tutorial later. But we can do a lot without caring about that yet.

Type Explanation
int For whole numbers, negative as well as positive.
[]  An array, for storing multiple instances of the rest of the variable types
float For storing numbers with a floating point. Numbers with a decimal fraction (1.5 or 3.141 etc).
char For storing a single alphanumeric letter.
bool This is a special variable that can only be one of two values; true or false. This type of variable is perfect for making decisions about what to do next. Is the enemy shooting? Is the game over? And much more. It is named after the eminent mathematician George Bool.
Class object Class objects can be nearly anything at all. They are a special type of variable which not only stores values but also behaviour. The player, a game character or even the game itself could be an object.

The table shows some key variable types that will help us to make some simple games in C++. The last one, Object, is the most powerful of all and will be covered in a later tutorial. We will, however, start meeting some of these objects/classes straight away in the SFML mini-projects.

How variables work

We can think of a variable as a kind of storage space. And when we declare a variable along with its type C++ not only reserves a space in memory, appropriate for that type but also links the name we give it to that space. So whenever we refer to playerScore we access whatever value is stored at a location in memory set aside for it. We don’t need to worry about how it works just yet or where in our computer’s RAM/CPU it is kept. In a later tutorial, we will look into this more, however. This leaves us free to work on the important aspects of our game without concerning ourselves about how computer memory is managed by our PC/Mac/Etc.

We prepare our variables in two steps; declaration followed by initialization. Let’s have a look at what the C++ code for this looks like.

Declaring a variable

We can declare a variable in C++ like this:

int playerScore;
char playerInitial;
float valuePi;
bool isAlive;

Above we simply state the type followed by the variable name and end the line with a semicolon. We add the semicolon to the end of the line to tell the C++ compiler that it is the end of the line. Notice that there are no array [] or object examples as they will be dealt with in later tutorials.

On line 1 of our code we have an int type variable (for numbers) called playerScore and on line 2 a char type variable (for textual data) called playerInitial. Next, on line 3 we have a float type variable called valuePi which can hold a decimal fraction that could represent pi (3.141…). Then on line 4 we declare a variable of the type bool to hold a true or false value, perhaps as to whether or not the player is still alive.

Initializing a C++ variable

Now we have declared the variables with meaningful names we can initialize those same variables with appropriate values, like this:

playerScore = 0;
playerInitial = 'J';
valuePi = 3.141f;
isAlive = true;

Notice on the end of the float initialisation we append an f. This is required in C++ to distinguish the number from other types that we can use. We could optionally combine the declaration and initialization into one step, like this:

Declaring and initializing in one step

int playerScore = 0;
char playerInitial = 'J';
float valuePi = 3.141f;
bool isAlive = true;

What next?

Of course, to make our variables any use at all we need to be able to read them and manipulate them.

If you haven’t already, you might like to consider Setting up Visual Studio and SFML as well as Building and configuring your first SFML game project ready to do some mini-projects after the next tutorial.

So let’s learn about changing the value of game variables with expressions.