3.1 Assignment Statements

[ Table of Contents ] Chapter Overview ] Next ] [ Glossary/Index ]

An assignment statement is a simple statement used to replace the value of a variable with a new value computed using an expression, as indicated below.

General Form

Variable_Name := expression;

After the expression on the right side of the := symbol is evaluated, it's type must match the type or subtype of the variable on the left. Otherwise, an exception will be raised.

Here is a small program containing two simple examples of assignment statements, one handling integer values and the other handling string values.

Source Code Listing

------------------------------------------------------------------
with Ada.Text_IO,
use  Ada.Text_IO;
procedure Assign_Integer_And_String_Values is
  X : Integer;
  Y : Integer := 5;
  Z : Integer := 2;
  First_Name : String := "Ada";
  Last_Name  : String := "Lovelace";
  Full_Name  : String(1..12);
begin
  X := 10*(Y + 6)-Z;                             -- assignment
  Put("X = ");
  Put(Integer'Image(X);
  New_Line;
  Full_Name := First_Name & " " & Last_Name;     -- assignment
  Put_Line("My name is " & Full_Name);
end Assign_Integer_And_String_Values;
------------------------------------------------------------------


The above program produces the following output:

     X = 108
     My name is Ada Lovelace

(The multiplication by 10 happens before the subtraction of 2.)

Operator Precedence and Overloading

The evaluation of expressions involves operators such as +, -, and * (for numeric values) and & (for strings and characters). The following table lists the precedence rules for Ada's built-in operators, ranging from level 6 operators (highest precedence) to level 1 (lowest precedence).

6 5 4 3 2 1
**, abs, not *, / , mod, rem +, -
(unary)
+, -, &
(binary)
=, /=, <, <=, >, >= and, or, xor

The level 1 operators are known as logical operators. The level 2 operators are known as relational operators. (See discussion of the Boolean type in the next chapter.) The binary (level 3) operators take two parameters, while the unary (level 4) operators take just one.

Some of the built-in operators are overloaded. For example, there are multiple versions of the binary +, -, * and / operators, used for different combinations of numeric types -- Integer, Float and Fixed_Point. (See discussion of numeric types in the next chapter.) It is also possible to create user-defined operators, which can further overload some of the symbols used for the built-in operators.

Related Topics

3.8 Exception Handling 4.1 Type System Overview
4.5 Numeric Types A.2 Simple and Compound Statements

[ Back to top of pageNext ]