Procedures and Functions in Ada: Modularizing Your Code

July 4, 2024

In this post, we explore procedures and functions in Ada for modularizing your code. Learn how to define and call procedures, pass parameters, and return values to enhance code reusability.

Procedures in Ada

In Ada, procedures are used to group a set of statements that perform a specific task. They help in breaking down a program into smaller, manageable parts. Here’s how you can define a procedure in Ada:

procedure SayHello is
begin
    Put_Line("Hello, World!");
end SayHello;

To call the procedure, you simply use its name:

SayHello;

Functions in Ada

Functions in Ada are similar to procedures but return a value. Here’s how you can define a function in Ada:

function Add(a, b: Integer) return Integer is
begin
    return a + b;
end Add;

To call the function and use its return value:

declare
    Result: Integer;
begin
    Result := Add(3, 5);
    Put_Line("Result: " & Integer'Image(Result));
end;

Parameters and Return Values

In Ada, you can pass parameters to procedures and functions to make them more versatile. Parameters can be of different types such as Integer, Float, Boolean, etc. Similarly, functions can return values of different types. Here’s an example:

procedure Multiply(a, b: Integer; Result: out Integer) is
begin
    Result := a * b;
end Multiply;

To call the procedure and retrieve the result:

declare
    Output: Integer;
begin
    Multiply(4, 6, Output);
    Put_Line("Result: " & Integer'Image(Output));
end;

By using procedures and functions in Ada, you can modularize your code, improve code readability, and promote code reusability. Understanding how to define, call, pass parameters, and return values from procedures and functions is essential for mastering Ada programming.