Variables in C++

C++, like most programming languages and mathematics in general, has variables that contain a value (typically a number).

We have already mentioned and used variables a few times: in relation to input and output, and in relation to types and assignments. This pages discusses the idea of variables in a bit more detail. Just as in mathematics, there are a number of important conventions that you must pay attention to.

1. Variables as boxes

You might think of a variable such as x in maths as a value, but it is more than that. It's also a letter, which has a value attached to it. So it describes a relationship between the letter and a particular number. And it's more complicated than that because the value I am thinking of today as being x is not the same as the one I was thinking about yesterday, so the relationship between the name x and its value also depends on context in some subtle way.

A variable in C++ such as X can be thought of as a labelled box, where the label is the letter and the box is the place the number (or other value) is placed. The label is not available for use at all times, but only in certain contexts. There may be several different boxes all labelled X available at different times, in which case most likely only one of them is available at any particular time.

Suppose I was writing a proof on the board, such as the proof that there are infinitely many primes. If I started saying that I wanted to consider the value y which is what you get when you square x , take its integer part and then take the factorial of the result, you would be perfectly in your rights to criticise me for not explaining what x is first. After all, how can we know what x 2 ! is if we don't know what x is? The same applies to computer programming.

A variable in C++ must be introduced by declaring it, i.e., telling the compiler that the letter or combinations of letters represents a variable. Without this the compiler would not know what the word "means".

Of course, just knowing what kind of variable it is doesn't tell you what its value is. In C++, declaring a variable means creating a box in memory for that variable, but it does not do anything to the contents of that box. C++ compilers usually create a box by marking out a bit of memory in the computer. It's like a computer version of a farmer that puts a fence round their new land before ploughing that land. Declaring the land as being yours is not the same thing as ploughing it. The land inside the fence is unchanged until the farmer remembers to do anything with it and (in the computer version) could be anything at all.

Each variable in C++ must be initialised before it is used.

Not initialising variables is one of the main reasons why a program that seems to work correctly on one computer fails to work on a different computer. Forgetting to initialise a variable is like "accidentally" nuking Birmingham. It might be difficult to forgive, even if it is accidental.

C++ allows a special shorthand for the combination "declaration and initialisation".

Do not use this abbreviation unless you know what you are doing! Some students discover that inserting type names such as int or double before variables in judiciously chosen places avoids annoying compiler error messages. Unfortunately, doing this without thinking usually also results in a program that doesn't work. This is not accidentally nuking Birmingham. This is more like "I don't know what to do, so let's see if my problems are solved if I press this button on this nuclear bomb".

What actually happens if you insert a type name such as int or double before a variable on the lefthand side of an = sign is that a new variable is declared (and its box created) with that variable name. In other words a new variable is set up in a new context. There is usually no reason why this variable can't have the same name as another variable in the program, but of course you can't use both at the same time. So the effect is usually to prevent access to a variable that you want to use, and muddle up two different variables with the same name. This is rarely what is wanted.

Every variable has a context, more properly called its scope, i.e. a part of a program where it is "visible".

Scoping rules will be covered later on a separate page.

2. How variables can change

In maths, variables are fixed. In a mechanics problem involving a differential equation, if we are looking at the position x of a particle at time t we are considering the particle at a fixed time and position throughout that part of the problem. (Yes, variables in maths have scoping rules too. The letters x and t do not have a fixed meaning for all problems.)

The big difference between variables in maths and variables in programming is that variables in programming are ... er .... variable, i.e. they can change.

Most programming languages, including C++, have special commands for "put this value in the variable X".

In many languages this is written as (for example) x := 3.14159; or x <-- 3.14159; or something like this to show that the operation inserts a value on the right into a variable on the left.

It is essential that you remember that = in C++ is not "equals" but something quite different.

Example.

To demonstrate copying and swapping int variables, copy and compile the following.

// vars-ex1.cpp (click here to download)

#include <iostream>

using namespace std;

/* demonstrates int variables and the assignment operator. */
int main () {
  int a,b,c,d,e;

  a = 1;
  b = 2;
  c = 3;
  d = 4;
  e = 5;
  
  cout << "a==" << a << " b==" << b << " c==" << c << " d==" << d << " e==" << e << endl;

  // now try and swap a,b
  b = a; // destroys old value of b
  a = b; // a becomes the new value of b

  cout << "a==" << a << " b==" << b << " c==" << c << " d==" << d << " e==" << e << endl;

  // now swap c,d, but do it properly
  {
    int x; // temporary variable
    x = c; // save old value of c
    c = d;
    d = x;
  }

  cout << "a==" << a << " b==" << b << " c==" << c << " d==" << d << " e==" << e << endl;
  
  // x is not in scope here:
  // e = x; // this would generate an error  

}

Exercise.

What does the C++ line x = x + 1; do?

The fact that variables can be changed is something that many beginners seem to forget. But it is extremely useful. Variables are like memories on a calculator, they can store intermediate values and such things like this. There is almost no limit to the number of variables you can have.

Remark.

If you are stuck on a problem and don't know how to program the computer to do something, one of your first thoughts should be "Do I have enough variables?" Or, "Should I declare more variables?" Sometimes this thought is enough to get you started.

Remark.

The opposite problem sometimes happens. Too many variables can lead to muddled thinking and muddled programs. Make sure you have exactly the variables you need, and certainly don't have two different variables for the same task.