Section 4.3 - Subprogram Bodies and Local Variables

A subprogram body defines the actual algorithm used by the subprogram. A subprogram body starts out with a subprogram specification (which is the subprogram declaration without the final semicolon) followed by the keyword "is". This is followed by a declaration of local variables, the keyword "begin", the statements to be executed, and then the keyword "end".

Here's a simple subprogram body that implements the procedure Average we declared in the last section. Note that after the word `end' we can add a word indicating what we're ending (the Ada compiler will check to make sure this is correct). Also note that the assignment statement in Ada is written as `:=' (the same as Pascal):

procedure Average(A, B : in Integer; Result : out Integer) is
 Result := (A + B) / 2;
end Average;

Local variables and local subprograms can be declared between the "is" and the "begin". Local variables and local subprograms exist as long as their enclosing subprogram exists. Local variables are useful as "scratchpads" to hold intermediate results. Local variables are written the same as parameters are: the variable name(s), a colon, and their type. They can be given initial values (the following example initializes its local variable `Total' to the value of A). Functions return a value using the `return' statement. Here's an example:

function Sum(A, B : in Integer) return Integer is
 Total : Integer := A;
 Total := Total + B;
 return Total;
end Sum;

Here's an example with a function that computes the sum of the squares of two Integers. It works by creating a local function called Square:

function Sum_Squares(A, B : in Integer) return Integer is

  function Square(X : in Integer) return Integer is
  begin -- this is the beginning of Square
    return X*X;
  end Square;

begin -- this is the beginning of Sum_Squares
 return Square(A) + Square(B);
end Sum_Squares;

Here's a BNF for subprogram declarations:

subprogram_body ::= subprogram_specification "is"
                    "end" [designator] ";"

declarative_part ::= { declarative_item }

declarative_item ::= object_declaration | subprogram_body

object_declaration ::= identifier_list : [constant] type [":=" expression] ";"

A brief note about statement sequences: like C, Ada uses semicolons as a statement terminator - each Ada statement ends in a semicolon. This is different than Pascal, which uses the semicolon as a statement separator.


Which of the examples in this section has an empty declarative_part (i.e. no local variables or subprograms)?

  1. procedure Average
  2. function Sum
  3. function Sum_Squares

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 4 outline

David A. Wheeler (

The master copy of this file is at "".