2.3. Local variables

It is often necessary to keep the result of an expression for later use. A good example of this is a counter: if you count from 1 to 10, when you're ready to go to the counter's next value you must know what its current value is. A local variable can be used to hold such values. For example, if a is a variable, then the assignment


a = 1;

will assign to a the value 1. When followed by the expression a + 7, the result of that expression will be 8.

As you will have guessed, each variable has a type. Before a local variable can be used, it must be declared, not only to indicate its type but also to declare its existence. The variable a used above would be declared as:


int a;

You can experiment with variables by modifying the main method of our example program again.


int
  main Array argv
{
  int a = 11, b = 6;

  [[[stdio out] print ("a = ", a, " b = ", b)] nl];
  int c = a * b;
  [[[stdio out] print ("a * b = ", c)] nl];
  c = a + b;
  [[[stdio out] print ("a + b = ", c)] nl];

  return 0;
}

This example shows that multiple variables can be declared in one declaration, and that an assignment to a variable can be included in its declaration. In fact, when such an initial value is omitted, the variable will be set to 0. Verify this by omitting the initialization of b (i.e., the `= 6') from the example and running the program again after rebuilding.

In general, if a variable declaration does not specify an initial value, the value of the variable will be the default value of the variable's type, e.g., 0 for numeric types and FALSE when the type of the variable is boolean.