The variables which we have been using in the functional model
(e.g.,
etc.) have no special meaning other than that they can be
instantiated with values of a given
type. These variables are similar to those used in algebra.
In contrast, in the imperative model we will use variables to store the state
of a computation. In this model, a ``declaration'' of variables to be of a certain type
with a statement like
int a,b;creates and reserves two locations (or boxes) with the names
a = 2;The above is read as ``
b = a;changes the state to
a = a + b;changes the state to:
On the left of the
operator must be a single variable whose state is being
updated, and on the right must be an expression comprising operators, variables and
values. The right side must evaluate to the same type as the variable specified
in the left.
As a result of this, in the imperative style, state changes can be performed only one at a time. Consequently, simultaneous changes in the values of several variables have to be performed in some orderly fashion, one-at-a time, so as to ensure that the desired final state is obtained through several one-step changes.
The state of the computation at any instant is a snapshot of the contents of all the variables used in the algorithm.
As an example of an imperative style algorithm using the assignment instruction, let us consider the following problem of swapping the contents of two variables.
| Pre-condition: |
|||
| Post-condition: |
/* assert
*/
temp = a; a = b; b = temp;
In the above example, the three assignment instructions have to be executed in the given order to achieve the exchange. An algorithm in the imperative model is a sequence of instructions which have to be executed in a step by step manner to carry out a desired computation. The instructions are separated by the symbol `;'. The sequence of three instructions may be regarded as a single compound instruction. To enable us to regard certain sequences of instructions as a single instruction we use a bracketing mechanism, where the left bracket is the symbol { and the closing bracket is the symbol }. Hence the above algorithm could be rewritten using brackets as follows
/* assert
*/
{
temp = a;
a = b;
b = temp;
}
As we will see the {...} brackets are very useful to avoid possible confusion.