C++: Variables and Constants

Variables are an extremely core concept to most object orientated programming languages. I like to visualize a variable much like a box. We can put things in the box, we can take things out of the box, and at any point we can see what is inside the box. Each box also has a name to which we can refer to it by, and in C++, each box can only hold a certain type of data.

When we create variables we call this the variable declaration, and then when we set them for the first time, we call this the initialization. To declare a variable in C++, we write the data-type that we want the variable to contain, followed by the variable's name, followed by a semicolon. One of the primitive data types is an integer, as we glossed over in the previous tutorial when talking about the "main" function. To declare a basic integer variable called "age", we could write the following:

1
int age;

From this point we can then refer to the variable by its name, so in this case, we can just write "age" whenever we want to refer to the variable. To initialise the variable we can write its name, followed by the equals sign, followed by the value we want to set the variable to (followed by a semicolon). The value we set it to can be a constant (a value that doesn't change), or another variable of the same type. An operator is a symbol which has a certain meaning in the programming language, in this case, the equals operator, represented by the = symbol, is an operator which sets whatever is on the left of the operator to whatever is on the right.

The constant value we set the variable to depends on the data-type the variable should contain - with integers (whole numbers), we can just write a normal whole number in the code (nothing special is required here). So we could initialize "age" to 5 with something like the following:

1
age = 5;

We can actually combine the variable declaration and initialization into one more-compact line, like the following:

1
int age = 5;

The "age" variable now contains the number '5', and we can refer to this '5' by writing "age" anywhere in our program. We can also change the value of the variable at any point by using the equals operator as we did for the first initialization:

1
2
3
int age = 5; //Declare "age" and set it to 5
age = 3; //Change "age" to 3
age = 21; //Change "age" to 21

Although this seems purely for convenience at the moment (as we could just write '5', '3', or '21' in place of "age"), trust me when I say that these become extremely useful and powerful when you start dealing with dynamic logic and user input (the latter of which we'll be covering later in this tutorial).

Just to give an example of accessing the contents of variables by using their names, we could create a new variable called "age_two" which is set to the value of "age", and then we can also try outputting one or both of these variables:

1
2
3
4
5
6
int age = 5; //Declare "age" and set it to 5
age = 3; //Change "age" to 3
age = 21; //Change "age" to 21
int age_two = age; //Declare "age_two" and set it to "age" (21)

cout << age << " " << age_two;

To be clear, all this code should be going into the basic program structure which we learnt how to create in the last tutorial. So we want our 'iostream' include for cout, cin, and some other stuff, we want the std namespace, and we want the majority of our code to be going in our "main" function. So our full code to demonstrate variables so far, which you can compile and run at any point to test the functionality, is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
	int age = 5; //Declare "age" and set it to 5
	age = 3; //Change "age" to 3
	age = 21; //Change "age" to 21
	int age_two = age; //Declate "age_two" and set it to "age" (21)

	cout << age << " " << age_two;

	return 0;
}

Some data-types come in 'signed' and 'unsigned' forms. If you don't specify a form, your compiler will just default to what you want most of the time (which is usually 'signed' for these). With integer variables, the difference is that "signed" number variables can handle positive and negative numbers, whereas "unsigned" number variables can only handle positive numbers, although because of this restriction, can hold larger numbers. You can write the signed or unsigned keywords before the data-type in the declaration to specify the form you want, for example unsigned int age;.

integers are not the only data-type that we can make use of in C++ either. There are a whole bunch of data-types which you can use, and we will go through some of the basic ones now.

Integers

Integers are the data-types we've covered most frequently up until this point. They can be declared by using the int type, and integer constants are defined by simply writing whole numbers. Signed integers on a 32bit computer can go from around -2147483647 to around 2147483647, and an example of a simple integer variable declaration and initialization to an integer constant is as follows:

1
int variable_name = 10;

Longs and Shorts

The "long" and "short" data-types are other forms of integer data-types which are for different lengths of integers. Longs are meant for holding longer numbers, however signed longs on a 32 bit computer can usually only hold numbers from around -2147483647 to around 2147483647, which happens to be the same as the integer range because longs and ints are often the same on computers these days. Shorts, meanwhile, are for holding shorter numbers - signed shorts on a 32 bit computer can hold numbers from around -32767 to around 32767. The advantage of using a short over an int or long when only short numbers are required to be stored, is that it takes up less memory.

Longs are declared by using the long data-type, and shorts are declared by using the short data-type, and the constants for both are simply written by writing the numbers. An example of simple variable declaration and initialization of both are as follows:

1
2
long variable_name = 312314121;
short variable_name = 5;

Floats

The "float" data-type represents "floating point numbers" - numbers with a decimal place in. Floats are accurate to around 6 or 7 digits and are declared using the float type. Float constants can be defined by simply writing a number with a decimal point followed by the 'f' notation. An example of a simple float declaration and initialization to a float constant is as follows:

1
float variable_name = 3.141f;

Care must be taken, however, with float (and other decimal) operations, as rounding and precision problems to do with how the numbers are stored can trip you up (we don't have infinite memory for recurring decimals like 1/3 for example) -- I recommend reading this article for more information on this if you're interested.

Doubles

The "double" data-type is very similar to the "float" data-type, but (usually) uses a different algorithm to store the data and is generally more precise, to around 15 digits (around double that of a float, hence the name). Double variables are declared using the double type and double constants are declared by simply writing numbers with a decimal point. An example of a simple double declaration and initialization to a double constant is as follows:

1
double variable_name = 3.14159;

Booleans

The boolean data-type is for storing true or false values. Boolean variables are declared using the bool type, and boolean constants are defined by either using the true or false keywords. An example of a simple boolean declaration and initialization to a boolean constant is as follows:

1
bool variable_name = true;

Chars

The character data-type is for storing single character values - for example 'a' or 'e'. Character variables are declared by using the char type, and character constants are defined by using single quotes (apostrophes) around the character. An example of character declaration and initialization to a character constant is as follows:

1
char variable_name = 'c';

Strings

The last data-type we're going to talk about in this tutorial is the string. We've talked about string variables in relation to cout before, and as such you should know that string constants are defined by using double quotes. String variables are declared by using the string type, however as strings aren't actually 'primitive' types in C++ (and are instead defined by the standard library of stuff that comes bundled with C++), you are required to #include <string> to use this data-type. An example of string declaration and initialization to a string constant is as follows:

1
2
3
4
5
#include <string>

//...program structure, main function etc...

string variable_name = "This is a string!";

Tying things off

With all those data-types covered, the best way for you to get used to them is really to just keep playing around with them. Trying using them with cout, and see if your compiler will do any automatic conversion from one type to another for you (if you set a new integer variable to a double variable, what will happen?).

Along with this, one of the finest ways to play around with string variables and create some programs with some basic functionality, is to make use of cin to get input from the user. As I hinted at just then, cin essentially just takes in a word (or small set of characters without a space) from the user, and then stores this in a string variable. To get data from the user in this way you simply write the cin keyword, followed by some extraction operators, >>, followed by the variable you want to put the result in (followed by a semicolon) - so cin >> variable_name;. Using this technique, we could take in the user's name and greet them using it with some code like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string name; //A string variable to store the user's name
	cout << "Enter your name: "; //Prompt the user for their name
	cin >> name; //Take input for the user's name and store it in our string variable, 'name'
	cout << "\nHello, " << name << "! It's nice to meet you!"; //Greet the user

	return 0;
}

As a small challenge to tie off the pieces we learnt in this tutorial - try creating a basic application which asks the user for some credentials and stores them in strings, outputting them all at a later point in the program. Right now it may seem as if all variables which aren't strings aren't massively useful, but this is just because we don't really know how to utilize all the functionality of different data-types yet - for example, we don't know how to perform simple mathematics on number types, or how to check the value of booleans to change the logic of the program. All will be revealed in future tutorials.