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; its value is not determined.

C++ differs from Java in its handling of uninitialized variables. Java insists that the program must store a value into a variable before the variable is used. C++ has no such requirement. If you use a variable that has not been initialized, you get whatever junk value is in that variable.

There is no way for a program ask whether a variable is uninitialized. 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.

Always be sure to initialize a variable before you use it.


Variable names

For a variable name, use a name that starts with a letter and can contain 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. But it is considered poor practice to use both Size and size as variables. It is confusing to a human reader.


Assignments

Changing the value of a variable is called doing an assignment to the variable; you assign the variable a value.

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. That is, it initializes 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 (optional)

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 can begin a compound statement {…} with statements that create variables, but you 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 there are some convenient abbreviations. Statement
  n++;
means the same thing as n = n + 1;. Similarly, statement
  n--;
is equivalent to statement
  n = n - 1;

Increment and decrement as expressions (optional)

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 also write ++ or −− in front of a variable. Expression ++n 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.

The coding standards require you to restrict use of ++ and −− to statements. 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.


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 you only want to compute the expression's value once. That is just a matter of storing the result of the expression in a variable so that 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 are done?

      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 is the value of variable x after doing the following statement?

      double x = 1/3;
    
    Answer