5.5. Variables

A variable can hold one item of a given type. If you store a new item into a variable, it replaces the old item.

Creating a variable

If T is a type and v is a name, then statement
  T v;
creates a new variable called v that can hold one item of type T. For example,
  long x;
creates a new variable called x of type long and
  double frog;
creates a new variable called frog of type double. You can create several variables of the same type together, as in
  double width, length, height;

No automatic initialization

When a variable of one of the numeric types, such as double or int, is created in this way, no particular value is stored in it. The variable is uninitialized.

There is no way for you ask whether a variable is uninitialized in a program. If you create a variable called x of type int, then x will initially hold some value of type int, but you have no idea what that value will be.


Variable names

For a variable name, use a name that starts with a letter and can have letters, digits and the underscore character. For example, x, show_me and index12 are acceptable variable names. Do not put a space in a variable name.

The case of letters matters. For example, Size and size are considered different variable names.


Assignment

Expression v = E computes the value of expression E then stores that value into variable v. The value of the expression is the value that was just stored into v.

Typically, you are not interested in the value, and you write a semicolon to indicate that. For example, statement

  x = y + 1;
stores one larger than the value of y into x.


Assignments are computed from right to left

Consider the following.
  int x;
  x = 0;
  x = x + 1;
The first line creates variable x. (The presence of the type, int, tells you that you are creating a new variable.) The next line stores 0 into x. (Notice that no type is written. We are using an existing variable, not creating a new one.) The third line starts by computing x+1, which is 1 since x is currently 0. Then it stores 1 into x.

Multiple assignments

Because assignment is an expression, you can use it on the right-hand side of another assignment. That allows you to write
  a = b = 0;
to store 0 into both b and a. Several = operations in a row are done from right to left, so the above is equivalent to
  a = (b = 0);

Creating initialized variables

When you create a variable you can also give it an initial value. Statement
  int r = 1;
is equivalent to the two statements
  int r;
  r = 1;
Creating and initializing several variables of the same type is easy:
  long w = 0, n = 1;

Restriction on creating variables in C (optional)

Although we are working with C++, it is worth noting some differences between C++ and C. In C++, you can create a variable anywhere. In C, you begin a compound statement {…} with statements that create variables, but cannot create a new variable after a non-variable-creation statement. For example,
  {
    int w = 1;
    printf("This is the second statement\n");  // Writes a string
    int r =0;
    …
  }
is allowed in C++ but not in C.

Increment and decrement operators

It is very common to find that you want to add 1 to a variable or subtract 1 from a variable (changing the value of the variable). Of course,
  n = n + 1;
will change n to have a value one larger than its former value. But you can also write
  n++;
to mean the same thing. Similarly, statement
  n--;
is equivalent to statement
  n = n - 1;

n++ is actually an expression. Its value is the value that n had before it was modified. So, for example,

  int n = 1;
  int z = n++;
ends with n = 2 and z = 1. You can write ++ or −− in front of a variable. Expression ++n also adds 1 to n, but its value is the value of n after it is changed. So
  int n = 1;
  int z = ++n;
ends with n = 2 and z = 2.

I recommend that you restrict use of the ++ and −− operators to statements. Misuse of them is a common mistake. For example, n++ is not the same as n + 1, since the former expression changes n but the latter does not. Never write something like

  n = n++;
A statement like that, which changes the same variable twice, has undefined behavior in C++. It does not necessarily do what you think it should do. See the coding standards.


Operator assignment

Statement
  x += k;
is equivalent to
  x = x + k;
You can use any binary operator (+, −, *, etc.) with =. For example, statement
  x *= n + 1;
has the same effect as statement
  x = x * (n+1);

Named constants

If you write const in front of a variable creation statement then you must initialize the variable and it cannot be changed after that. For example,
  const int maxNumberOfEdges = 100;
creates constant maxNumberOfEdges. Once it has been created, you are not allowed to change its value.

Remark. As long as you use types such as int and double, the description above is correct. But there is more to what const means that we will see later, and it does not always mean what you might guess it means. We will see examples of that later. (optional)


Assignment uses current values of variables

Statement
  x = y;
does not make x permanently equal to y. It only says to put the current value of y into x. For exaple,
  y = 0;
  x = y;
  y = 1;
ends with x = 0 and y = 1.


Some uses for variables

Using variables to avoid computing something twice

Sometimes you want to use the value of an expression in two places, but only compute the expression once. That is just a matter of storing the result of the expression in a variable so the the program remembers it. See the next item.

Using variables to make programs more readable

Some expressions are long and complicated. Using variables can simplify them. For example, imagine computing the two solutions for x to equation ax2 + bx + c = 0. The following does the job.
  double disc  = b*b - 4*a*c;
  double s     = sqrt(disc);
  double twoa  = 2*a;
  double soln1 = (-b + s)/twoa;
  double soln2 = (-b - s)/twoa;
Notice that s is computed once but used twice. Variable disc is just used to shorten an expression. (You also might want to test whether disc ≥ 0, since otherwise the expression sqrt(disc) causes an error.


Exercises

  1. Is there a default value to which variables of type int are initially set? Answer

  2. What are the values of variables r and w after the following statements?

      int r = 24;
      int w = r+1;
      w+1;
      r++;
    
    Answer

  3. Rewrite the following so that it does not compute max(x,y) twice.

      int x = max(x,y)*max(x,y) + 1;
    
    Answer

  4. Is the following sequence of statements allowed?

      int d = 40;
      int d = d + 1;
    
    Answer

  5. Is the cat an acceptable name for a variable? Answer

  6. If you use a variable that you have not created, will the compiler create it automatically for you? Answer

  7. What does expression n++ do? Answer

  8. What does expression ++n do? Answer

  9. What is the value of variable x after doing the following statement?

      double x = 1/3;
    
    Answer