A Comprehensive Guide to Variables in C++

You can access the full course here: C++ Programming for Beginners

Basic Variables

As fun as input output is, it’s time to start learning about the language basics so we can make our programs actually do something significant. There’s no better place to start than with variables. Variables are a fundamental component of every program ever written. They provide a way to store and modify values as the program runs. Variables have a name, a type, and a value where the type dictates the kind of data that can be held (text, number, etc.). C++ is statically typed meaning once a variable is assigned a type, it cannot change (unlike dynamic languages like Python). The basic types are:

  • bool
  • int
  • float
  • double
  • char
  • nullptr
  • void
  • string

Technically strings are not basic variables; they are considered to be an array of characters or chars. In fact, the C language doesn’t even have strings. C++ is high level enough that they at least allow us to use strings. Before we dive into each variable type let’s talk about declaring vs initializing.

Declaring a variable is just assigning a name and a type. This can even be done outside of a function. Essentially, the compiler allocates some space for it (depending on the type of variable) but doesn’t store a value. Initializing a variable is assigning a value to it. We need to make sure the value we assign matches the type. We can break the process of creating variables into these 2 different parts or do it all at once. Our .h files can be used to declare variables and the .cpp files are used to initialize them (among other things).

Just a heads up; until otherwise stated, any code that you want to write to practice or follow along should go between the { } in the main function, otherwise you won’t be able to run it.

Booleans

Let’s start with Booleans or bool. These are true or false values; if the value is not true, it’s false and vice versa. Use these when you need a variable that can only take on one of two values such as:

bool isGameOver = false;

A game is either over or not; there are only two possible states (pausing a game still falls under the category of not over). We could split this up into:

bool isGameOver;
isGameOver = false;

If we wanted but it doesn’t matter here. We can also assign the result of some comparison operation like this:

bool isFalse = 5 > 10

5 is not greater than 10 so this stores false.

Numbers

There are 3 basic numerical types in C++ int, float, and double. There are actually variants on these such as unsigned int for when we just want positive numbers or ints with a specific number of bits. That’s beyond the scope of the course so let’s ignore those for now. Use integers or int when you want whole numbers:

int xPos = 5;
int yPos = -2;

Use floats or doubles when you want decimal numbers:

float percentHealth = 0.45;
double pi = 3.14159;

Doubles offer more decimal places than floats but nothing we will be doing here will require that precision so we’ll stick with just floats.

Numbers can also store the results of an arithmetic expression such as:

float percentHealth = 80 / 100;

Characters

Characters, or char, are single digit text variables between the single quote: ‘’. For example:

char c = ‘c’;

With strings available, the character type is not used too often. They potentially (but not necessarily) take up less space in memory but are more difficult to work with as you have to convert back and forth to combine them.

Nullptr

Nullptr is a value assigned to a pointer when we don’t have anything for it to point at. That likely won’t mean a lot just yet so we’ll skip this one for now and come back to it when we talk about pointers.

Void

Void is used in two cases: when we don’t want to output a specific value from a function or when we don’t want to take any parameters as input. When used with pointers, this means that it could be a pointer of any time. Again, that won’t mean a lot right now so let’s ignore this one too.

Strings

We’ve already seen some of these in our code examples! Strings represent text data such as messages or names and are initialized between double quotes: “”. Unlike characters, they can be of any length including 0. These are part of the std library so you have to use the special std:: syntax or include using namespace std. Some examples might be:

std::string name = “Nimish”
std::string emptyString = “”;

 

Transcript

What is up everyone and welcome to the fifth tutorial in our “Learn C++” course. This will be on variables, and is part one of two just because there is quite a lot to take in with regards to variables, and I don’t want to overwhelm you with everything all at once. So in part one, we’re going to focus on what are variables. Then we’ll talk about some of the basic variable types in C++, these will be in the slides, and then we’ll turn to the code and focus on assigning and reassigning variables with some examples.

So for starters, what are variables? Variables is simply a way to store and modify data within a program. Pretty much every program will need some kind of variables to help maintain its state throughout its execution. Variables can be used temporarily or can exist throughout the entire program’s execution.

Take for example a game, often they’ll ask what your name is right at the beginning, and then they’ll store it somewhere. Well, that name will exist throughout the entire time that you’re playing the game, and also in future runs as well. However, if we’re entering, let’s say a specific level, there may be a lot of variables that help set up the level that are basically destroyed, as soon as we leave the level or go into a different one.

Now, each variable uses a “type” to dictate the kind of data that can be stored. So there might be, let’s say, numerical types of variables, well there may might be text based variables or true false variables, these are all determined with the type which we have to assign. Creating a variable can be broken down into two stages; declaration and initialization. Declaration is essentially assigning a type and a name to a variable. And then initialization is storing a value in that variable.

So some of the types in C++. For starters, C++ is statically typed. So statically typed means once we assign a type to a variable, that type can never change. If we create let’s say, a numerical variable, we cannot then later store a true or false value in it. Now this is unlike languages like Python, which are considered dynamically typed, those definitely allow you to modify types of variables, but C++ is a bit more rigid that way.

So some of the basic types we might encounter will be Booleans, which are true or false values, integers, which are positive or negative whole numbers, floats and doubles, which are decimal numbers, characters, which are single byte characters, and then there are null pointers and void types.

Now, null pointers and voids are a little bit more advanced, so I doubt we’ll actually cover those too much in this course, but I just wanted to include them here just in case some of you say, “Well, there are actually other types and you didn’t include them.”

Okay, so I think we’ll focus on bools, ints, floats. We might take a look at some doubles, but we’ll kind of skip over those for the most part because they’re actually quite similar to floats, and the characters and strings, we’ll actually cover in the next tutorial.

So let’s head on over to the code and go over at some examples. Okay, so as you can see, I’ve kind of cleared out my main file and put everything in old code. And I’ll continue to do that as we go. All right, so the first stage is going to be talking about how to declare and initialize variables.

So the two stages are gonna be assigning a type and a name, okay. So that will be the declaration and then initialization will be name equals some value, okay. We can do this in two steps, or we can do it in one like this.

So let’s focus on Boolean variables, because they’re the simplest. The type is gonna be a bool, okay? The name is gonna be whatever we want. Let’s think about something game related, so maybe it’s something like “isGameOver”, okay? And then we can leave it at that. We can then assign it in a value. So isGameOver is equal to false because maybe the game is still running, okay? So Boolean is perfect for this kind of a variable, because the game is either over or it’s not over. So even if it’s paused, that doesn’t mean the game is over it’s technically still running. So it’s either true or false. There’s only one of two possible states.

Okay, so we can put this all in one go if we want suppose saying bool isGameOver is equal to false doesn’t really matter too much. So we’re actually gonna break it up. Okay, if later on, we decide that okay the game is over, we died, or maybe we just won, then we’re just going to say; isGameOver is equal to true. So this is assigning the value for the first time and then this is reassigning it later on.

We can also perform other operations, we can have a another variable such as bool isNotGameOver. I know this doesn’t really make too much sense, but just bear with me here. And we can assign it the value of isGameOver. So basically, this will say whatever value we find here true, we’re just going to copy that into here, okay.

So at this point in time they’re equal but then I could reassign it later. So I could say isGameOver is equal to, you know, false again, and then this one doesn’t change, okay? So just something to note there. We can also take Boolean values and assign them the value of some comparison operation. So for example isGameOver is going to be equal to five greater than two. Now I know this really doesn’t make much sense, given our context, but this is a perfectly valid operation, because five is greater than two, it stores the value of true, okay? So again, something to note there. Just interesting semantics.

Okay, so that’s Booleans for you, they’re very simple. Again, it’s either true or false, there’s not too much more to know there.

So next up is gonna be integers. So integers are whole numbers. Can be positive or negative. And as you can see, there are a ton of variants. So we’re not gonna worry about any of these, like int 16 and 32. There’re also like unsigned integers, if you go all the way down. We’re not gonna worry about those. We just don’t really need that level of specificity. So we can kind of ignore that.

So an int let’s say, let’s say currentHealth, okay? Maybe is equal to 100, okay. So again, we can we can split this into two parts, we could do this and say currentHealth is equal to 100. Or we can do it all in one go. Let’s do it all in one go just for the sake of variety here. We can also take our integers and we can assign them the value of some operation two but it shouldn’t be a comparison operation cause this returns true or false, and doesn’t return a number.

But we could do something like currentHealth is equal to 50 minus two, for example, and that’s also perfectly valid. We’ll talk more about operators like this later on. For now, just know that it’s totally possible to do so. Just like with Booleans, we can assign them a literal value like this, or we can assign them the value of some other variable, that’s entirely up to us what we wanna do with them.

Okay, so finally, we’ll move to floats and doubles. Floats and doubles are both decimal numbers, but doubles offer double the precision of floats. That’s how they get the name interestingly enough. So if a float is a decimal number, then a double will potentially double the amount of decimal places it can hold. Like I said, I don’t really use doubles very much, because I just don’t need that level of precision. And they would take up a bit more memory.

So as much as possible, we’ll stick to floats. If we really, really need to be precise, then we can use doubles instead. But we’ll do floats, let’s say, maybe we’ll do like percentHealth or something like that is going to be equal to 0.45. And that would be a perfectly valid thing. Just like with, I’ll show you an example of doubles, because why not?

Let’s say pi, for example, so 3.14159 probably shouldn’t add extra decimal places if I don’t need them. So that would be an example of a double or a float. Now I could totally use a float to represent this, that’s fine. You’ll note that if actually if I scroll over it, you can see that it’s storing all of these values here, but this is not going to store quite as many values in there.

All right, one final thing I should say is that we can’t assign decimal numbers to integers. But we can assign whole numbers to doubles or floats, okay. So I could totally do five, and that’s fine, okay. Just like I could do 5.9, it would be interpreted as 5.0. But if I did five, that would also be fine, okay?

We should also be aware that if we are doing operations, such as a whole number minus a decimal number, then we can’t store that inside of an integer, we would have to use a float or do some kind of conversions to make sure that we’re dealing with variables of the same type. We’ll talk more about that when we get to operators and operations, but you know, just keep that in mind as we go.

Okay, so that’s it for now. We covered Booleans ints, and floats and doubles. When we come back, we’ll talk quickly about characters and then move to strings. So thanks for watching. See you guys in the next one.

What’s up guys, welcome to the sixth tutorial in our Learn C++ course, here we’ll cover part two of variables, there’s only two types we really need to go over, and those are going to be characters and strings in C++.

So, we’ll just quickly talk about characters, these are simple text-based variables, they’re used for single digit texts only, and as basically anything of length one between the single quote marks, Okay? So it cannot be length zero, it cannot be length two, three, four et cetera, has to be of length one. There’s a great way to represent special characters such as newline or return characters, otherwise, I personally don’t really use them that much.

Next up is gonna be strings, these are text-based variables, we’ve actually seen some examples of these already. These are used for texts, names and messages throughout our code, and it’s basically anything between these double quotes. Unlike the characters, they can be of length zero, one, two, three, four, etcetera basically, up until an infinite length well – not quite because that would actually crash a program, but they could be very, very big, Okay?

So let’s head on over to the code and take a look at some examples. Right, so once again, cleared everything out. So the first thing is going to be our characters. Now these are aside from Booleans, the simplest, I guess, simplest type. But just because they take up the second least amount of memory, it’s just by default take up eight bits, characters are four Booleans are actually just the one. But again, that’s kind of beyond the scope of the course. Okay?

So first of all, we can create a character with C-H-A-R, and all the char, okay? And we can call this whatever we want, so maybe let’s call this character G, okay, single quotes, and we’ll just put the G there, and just like that, all right. So similarly, the characters can have, Oh gee I guess I can’t call this character period. I can do that by couldn’t call it this, okay. If I did a character period like that, that’s also fine. And I could also have numbers as well. So I can do a character one is equal to one like this, okay? So there’s no restriction as to what I can put in there, it just has to be of length one only.

Like I said, I really don’t find myself using characters very often because we have strings, which are so much more powerful. So why use a character instead of a string? Well, the only reason I could really think of is if we are using special characters that just don’t really have a good string representation, which doesn’t really happen very often. And if we just don’t need something that has the functionality of a string.

Strings are actually considered arrays of characters. And in languages like C which are very, very low level, even more low level than C++, there is no string type. We have to use arrays of characters, so it gets to be a bit hairy. If you’re coming from C, then probably will be very familiar with characters. If you’re just hanging out with C++ and you have strings, you really don’t need to worry about characters so much.

Okay, so next up is going to be strings. So if we didn’t have the namespace standard, we would have to declare them as standard string, okay? Otherwise we can actually just say string. We’ll give this the name. So let’s do like a player name. And let’s just put our name, so it needs to be between the double quotes here, otherwise, doesn’t really matter what it is. We can do string empty, and we can have it like this. That’s a perfectly valid string as well, we can have a really long string, I’m not going to type out a really long string, but we could totally do that.

Also, I should note, because the strings are kind of considered arrays, there are a host of functions that come with strings. So we can do let’s say, empty dots. And then you’ll see a list of all of these strings. So you can append a string onto the end of it. You can get the beginning, you can clear it out to kind of get rid of all of the characters and just make an empty string. You can copy it, you can empty it, you can erase it. You can get the length or the max size, so on and so forth. You can pop out the last character, so you get rid of that last character in the string. And there are a ton of functions.

Just to kind of demonstrate one, I’m actually gonna to do the player names. It’s a bit more interesting. The player name, and we’re gonna to get the length of that. Okay, we can get it like this. And let’s say I want to output it, what I could do is, I could just say actually C out, okay, and then just play it name dot length. Like that. Okay, good stuff. Oh, and actually I have this facing the wrong way. Okay, cool. So if I give the Save and I give it Run, you can see I get six. And that makes sense because Nimish has six characters.

Okay, so feel free to play around with those functions a little bit. Again, the best way to learn how to code is to try stuff yourself and practice. So try out some of these other functions, okay? And just note that some of them will take in arguments, so for example, if I want to append some other string onto the end of it, okay, and then I wanted to print that out, I would have to do something like this, and then say C out, player name, if I can actually spell it properly. Okay? And you should see like a bunch of characters on the end of it.

So some of these arguments, some of these functions rather take in arguments like this, and some of them don’t need arguments. So for example, if you’re just guessing the side or the length, then it doesn’t matter. Okay, so once you’re done playing around with those, we’ll come back and we’ll focus on pointers. Now pointers get a little bit more complex. So make sure you’re super comfortable with all of these types that we’ve discussed before moving on to the next section.

Alright, thanks for watching. See you guys in the next one.

Interested in continuing? Check out the full C++ Programming for Beginners course, which is part of our C++ Programming Bundle.