Section 1.4 - Simple Variable, Integers, Parameters and Exceptions

Let's create a program to show what a simple variable and parameter-passing look like. This program will print out powers of 2, starting with 1, ``forever''. We'll call this program procedure Compute.

Inside this procedure create a local procedure called Double which doubles any number given to it, and a local integer variable named `X'.

-- Demonstrate a trivial procedure, with another nested inside.
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
 
procedure Compute is

 procedure Double(Item : in out Integer) is
 begin -- procedure Double.
   Item := Item * 2;
 end Double;

 X : Integer := 1;   -- Local variable X of type Integer.

begin -- procedure Compute
 loop
  Put(X);
  New_Line;
  Double(X);
 end loop;
end Compute;

Note that the local variable called `X' is of type Integer with an initial value of one. Integers are used when you want to store possibly signed integers, and you don't care what the minimum and maximum range is. As we'll see later, there are other things you should do if you do care what the minimum and/or maximum range is.

Inside this new procedure is a local procedure called `Double', which takes a value and doubles it. A local procedure, like a local variable, can only be used inside the procedure surrounding it. This capability to nest procedures inside other procedures is useful in larger programs and is a standard capability in Pascal (though not in C or C++).

The phrase `in out' means that the value is both received and changed in the procedure.

The phrase "with .. Ada.Integer_Text_IO" permits use of a predefined Ada 95 package for performing text input and output on Integers. It includes an operation named "Put" that will print an Integer sent to it.

The second `begin' statement defines the Compute procedure itself. Compute has an infinite loop, which prints the current value and doubles it repeatedly. `Put' prints out the number, and `New_Line' causes the text to go to the next line.

Computers can't really compute an infinitely large value; sooner or later they'll run out of space to store the number. What will happen in this case? Some programming languages (notably C) simply permit garbage to be computed. Ada has a better approach: when a computation (such as doubling) cannot be performed, Ada raises an `exception'. Thus, sooner or later this program will halt with a message explaining why and where it halted. As we'll learn later, these exceptions can be caught and handled inside the program.


Quiz:

When a computation cannot be performed, what does Ada normally do?

  1. Silently give the wrong answer
  2. Raise an exception
  3. Corrupt memory

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 1 outline

David A. Wheeler (dwheeler@dwheeler.com)

The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s1sf.htm".