Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Subprograms and Packages

Overloading, Nested Subprograms and Recursion in Ada

Use Ada features that shape larger programs: overloading subprograms and operators, user-defined operators, nested subprograms with access to outer variables, forward declarations and recursion.

Three techniques keep subprograms small and expressive: overloading (several subprograms share a name), nesting (a subprogram declared inside another can use its outer variables), and recursion. Ada supports all three with stricter rules than most languages, so they stay readable.

Ada code is read-only on this site; C stand-ins run.

Overloading

Two subprograms may have the same name if their parameter or result types differ:

ADA
function Max (A, B : Integer) return Integer is
begin
   if A > B then return A; else return B; end if;
end Max;

function Max (A, B : Float) return Float is
begin
   if A > B then return A; else return B; end if;
end Max;

function Max (A, B, C : Integer) return Integer is (Max (Max (A, B), C));

The compiler picks the version from the argument types. If the choice is ambiguous, you get a compile error rather than a silent guess. Unlike C++, the result type can also take part in the decision, as in Color'Val-style conversions. Enumeration literals are overloaded the same way (Red may belong to several types).

Operators are functions

Every operator in Ada is an ordinary function whose name is the operator in quotes. You can define new ones for your own types:

ADA
type Vector is record X, Y : Float; end record;

function "+" (L, R : Vector) return Vector is
   (X => L.X + R.X, Y => L.Y + R.Y);

function "*" (K : Float; V : Vector) return Vector is
   (X => K * V.X, Y => K * V.Y);

A : Vector := (1.0, 2.0);
B : Vector := A + (3.0, 4.0);       --  uses "+" above
C : Vector := 2.0 * B;

You cannot invent new operator symbols (no **=), and the precedence is fixed. The relational = may be redefined, and /= then follows automatically. Calling the function form is also legal: "+" (A, B).

Nested subprograms

A subprogram may contain its own declarations, including other subprograms. Inner ones are invisible outside and can use the outer variables directly:

ADA
procedure Report (Values : Int_Vector) is
   Count : Natural := 0;

   function Is_Big (X : Integer) return Boolean is (X > 100);

   procedure Tally (X : Integer) is
   begin
      if Is_Big (X) then
         Count := Count + 1;           --  uses the outer variable
      end if;
   end Tally;
begin
   for V of Values loop
      Tally (V);
   end loop;
   Put_Line (Natural'Image (Count) & " big values");
end Report;

This keeps helpers close to where they are used and avoids global variables. Each nested subprogram can use the enclosing scope's names, which is called static scoping. If two subprograms call each other, declare one first with a forward declaration (a subprogram specification followed by ;) and write its body later.

Recursion

A subprogram may call itself:

ADA
function Factorial (N : Natural) return Positive is
begin
   if N <= 1 then
      return 1;
   else
      return N * Factorial (N - 1);
   end if;
end Factorial;

Recursion is simple and expressive, but each call uses stack space. For systems with a fixed stack (embedded and safety-critical), many coding standards forbid recursion, or require an explicit depth bound. Ada has no guaranteed tail-call optimization. SPARK can prove termination if you provide a measure that decreases on every call.

flowchart TD
    A["Factorial (4)"] --> B["4 * Factorial (3)"]
    B --> C["3 * Factorial (2)"]
    C --> D["2 * Factorial (1)"]
    D --> E["returns 1"]

Each call waits for the next; when the base case returns, results multiply on the way back.

Stand-in: dispatch by type, nested helpers and recursion in C

C has no overloading, so the stand-in uses _Generic (C11) to pick max by argument type, which is the closest equivalent. It also shows a recursive function with a depth counter in the style of safety-critical code.

C Stand-in: overloaded Max and recursion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A second stand-in models overloaded operators on a Vector using plain functions, and nested-helper access to outer variables by passing a context struct, which is what the compiler does behind the scenes for static scoping.

C Stand-in: vector operators and an outer variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Overloading functions that differ only by parameter names or by mode (not allowed).
  • Creating ambiguous overloads that force callers to use qualified expressions.
  • Unbounded recursion with no depth limit.
  • Overriding = on a type in a way that is not symmetrical or transitive.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Ada choose among overloaded subprograms?

    The compiler resolves the call from the types; an ambiguous call is rejected.
  2. 2. How do you declare a user-defined addition for a record type Vector?

    Operators are functions whose names are the operator symbol in double quotes.
  3. 3. What can a nested subprogram do that a library-level one cannot?

    Nested subprograms see the declarations of the enclosing scope, so no globals are needed.
  4. 4. Why do many safety-critical standards restrict recursion?

    Bounded stack usage is required for predictable embedded systems.

Summary

  • Subprograms can be overloaded; the compiler resolves by types and rejects ambiguity.
  • Operators are functions named with quoted symbols and can be defined for your own types.
  • Nested subprograms keep helpers local and can use the enclosing scope's variables.
  • Recursion is supported; bound its depth in resource-constrained code.

Next: Derived Types and Subtypes: Strong Typing in Practice