The assignment statement is used in Ada to perform computations. The assignment statement
SquareYards := MetersToYards * SquareMeters;in Program 2.6 assigns a value to the variable
SquareYards
, in this case
the result of the multiplication of the constant MetersToYards
by
the variable SquareMeters
. Valid information must be stored in
both MetersToYards
and SquareMeters
before the
assignment statement is executed. As shown in
Figure
2.2, only the value of SquareYards
is affected by the
assignment statement; MetersToYards
and SquareMeters
retain their original values.
Figure 2.2
SquareYards := MetersToYards *
SquareMeters;
The symbol SYNTAX DISPLAY :=
is the assignment symbol in Ada and should
be pronounced "becomes" or "takes the value of" rather than "equals." The : and
=
must be adjacent characters with no intervening space. The
general form of the assignment statement is shown in the next display.
Assignment Statement (Arithmetic)
:=
expression ;
X := Y + Z + 2.0;
Table 2.2
Some Arithmetic Operators
Operator Meaning + addition - subtraction * multiplication / division ** exponentiation
It is permissible to write assignment statements of the form
Sum := Sum + Item;where the variable
Sum
is used on both sides of the assignment operator.
This is obviously not an algebraic equation, but it illustrates something that
is often done in programming. This statement instructs the computer to add the
current value of the variable Sum
to the value of
Item
; the result is saved temporarily and then stored back into
Sum
. The previous value of Sum
is destroyed in the
process as illustrated in
Figure
2.3; however, the value of Item
is unchanged.
Figure 2.3
Sum := Sum + Item;
Assignment statements can also be written with an expression part that consists of a single variable or value. The statement
NewX := X;instructs the computer to copy the value of
X
into NewX
. The
statement
NewX := -X;instructs the computer to get the value of
X
, negate this value, and
store the result in NewX
(e.g., If X
is 3.5,
NewX
is -3.5; if X
is -17.4, NewX
is
17.4). Neither of the assignment statements above changes the value of
X
.
X = Y; A := B - C; P + Q := R; G := G; H := 3 + 4; H := 3 + K; T := S * T;
Copyright © 1996 by Addison-Wesley Publishing Company, Inc.