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 begin 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; begin 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" declarative_part "begin" sequence_of_statements "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)?
![]() |
![]() |
![]() |
---|
David A. Wheeler (dwheeler@dwheeler.com)
The master copy of this file is at
"http://www.adahome.com/Tutorials/Lovelace/s4sf.htm".