Changing the Value of a Name


Variables

So far we have used names to refer to values, but once a name is used in a particular context, it keeps referring to the same value. In this chapter we introduce variables, which can change their values while the program runs. Variables will be used extensively in subsequent chapters.


Changing the value of a variable

After you have given a value to a name using a Let statement, you can change its value to something else using a Relet command. For example,

  Let x: Integer = 3.
  ...
  Relet x = 7.
first makes x = 3, but then changes its mind and makes x = 7.

The new value of a variable can be given by any expression, including an expression that uses the old value of the variable. The expression is computed first, then the value of the variable is changed. For example,

  Let x = 2.
  Relet x = x + 1.
starts by making x = 2. Then the Relet command is performed, in two steps. First, it computes x + 1. Since x is currently 2, that expression has value 3. Next, the value of x is changed to 3.


Type requirement

There is an important requirement about types. When you create a variable (using Let) you establish its type, regardless of whether you explicitly write the type or not. All future Relet's must use a value of the same type. For example,

  Let z = 2.
  Relet z = "boat".
is not allowed since variable z was created holding an integer, and so it must always hold an integer.


Hand simulation with Relets

When you use Relet-statements, you will want to do careful hand simulations. Show each variable. When you change the value, cross out the old value and show the new one. For example, a hand simulation of

  Let x = 2.
  Relet x = x + 1.
starts by indicating that x is 2.
x
2
Simulating the Relet-statement changes the value of x to 3.
x
 2 
3


Problems

  1. [solve] Show a careful hand simulation of the following.

      Let x = 35.
      Let y = 100.
      Relet x = x + 1.
      Relet y = y + x + 2.
      Relet x = 1000.
    


Summary

You can change the value of a variable using Relet.

In a given context, a given variable always has to have the same type.

It is a good idea to do a careful hand simulation, crossing out the old value of a variable when its value is changed.


Review

In Cinnameg, it is important to choose variable names that start with lower case letters.

You can write type information in your programs and function definitions. Doing that tends to make programs easier to understand. Types include Integer, Real, Boolean, Char and String.

To build a complete Cinnameg program, write Define ... %Define around each function definition and write Execute ... %Execute around the steps to be performed.