Thursday, August 16, 2012

AdaTutor - Operators and Control Constructs (4)

Brief Overview of Functions

   procedure Funct_Demo is
     X : Float := 1.2;
     Y : Float;
     function Twice(Dummy : in Float) return Float is
       Answer : Float;
     begin
       Answer := Dummy * 2.0;
       return Answer;
     end Twice;
   begin
     Y := Twice(X);
   end Funct_Demo;

Let's look briefly at functions so we can do Outside Assignment 2; later, in the section on Subprograms and Packages, we'll cover functions and procedures in detail.  Here procedure Funct_Demo locally declares a function Twice.  Twice can be called only from within Funct_Demo; here the call is Y := Twice(X);.

The function specification gives the name (Dummy), mode (in), and type (Float) of any formal parameters, or "dummy arguments."  The mode can be omitted, in which case the compiler will assume the mode to be in. The function specification also gives the type being returned, in this case Float.

In the case of functions (as opposed to procedures), the mode of all parameters must be in, never out or in out.  For this reason, many programmers omit the mode of function parameters, but we think it's a good idea always to show the mode explicitly.

The function body must have return followed by an expression of the right type.  This is usually the last statement before end.  We don't return a value by placing the name of the function in an assignment statement, as in Fortran.  Of course, function Twice could be written more simply as

   function Twice(Dummy : in Float) return Float is
   begin
     return Dummy * 2.0;
   end Twice;

It's even better to place the function in a separate file and compile it later.

   procedure Funct_Demo is
     X : Float := 1.2;
     Y : Float;
     function Twice(Dummy : in Float) return Float is separate;
   begin
     Y := Twice(X);
   end Funct_Demo;

   separate (Funct_Demo)
   function Twice(Dummy : in Float) return Float is
   begin
     return Dummy * 2.0;
   end Twice;
With most compilers the calling program can then be compiled once, and later the function can be edited and recompiled as often as desired.  Twice is still local to Funct_Demo.  The phrase separate (Funct_Demo) tells Ada that this subprogram is part of the previously compiled unit Funct_Demo.  It's as if the function were cut out and "pasted" where the calling program says function Twice ... is separate;.  Ada can still compile the call Y := Twice(X); because the calling program contains the specification of the function.

< prev   next >

Post a Comment