wtd
|
Posted: Sun Oct 10, 2004 1:48 am Post subject: [Ada-tut] Functions and procedures |
|
|
Some background
Functions and procedures are a basic way of giving a name to meaningful and often repeated bits of code.
A small surprise
As we've seen, a basic Ada95 program is contained within a procedure. It may strike you as odd then that we can define functions and procedures within this procedure. In Ada95, a procedure or function may contain other functions and procedures.
A few simple examples
Let's define a function which returns 42.
code: | procedure Simple_Program is
function Forty_Two return Integer is
begin
return 42;
end Forty_Two;
begin
end Simple_Program; |
Functions are easy, since they don't alter anything outside of them. Procedures act on external things, so we'll need to create a variable for a procedure to act on.
code: | procedure Simple_Program is
function Forty_Two return Integer is
begin
return 42;
end Forty_Two;
My_Int : Integer;
begin
end Simple_Program; |
Now let's create a procedure which sets My_Int to 42.
code: | procedure Simple_Program is
function Forty_Two return Integer is
begin
return 42;
end Forty_Two;
My_Int : Integer;
procedure Set_My_Int is
begin
My_Int := Forty_Two;
end Set_My_Int;
begin
end Simple_Program; |
And calling the Set_My_Int procedure, which calls the Forty_Two function is as simple as:
code: | procedure Simple_Program is
function Forty_Two return Integer is
begin
return 42;
end Forty_Two;
My_Int : Integer;
procedure Set_My_Int is
begin
My_Int := Forty_Two;
end Set_My_Int;
begin
Set_My_Int;
end Simple_Program; |
Parameters
Functions or procedures which can't accept data and act on it are rather useless. Fortunately Ada95 provides simple and easy syntax for passing data to functions and procedures.
Let's rewrite our previous example with a function Double_It, which returns the integer passed in, multiplied by two, and a procedure Double_Me which passes its parameter to Double_It and assigns the result to that variable.
Of course, we'll also need a vriable to pass to the procedure.
code: | procedure Simple_Program is
function Double_It(X : in Integer) return Integer is
begin
return X * 2;
end Double_It;
procedure Double_Me(X : in out Integer) is
begin
X := Double_It(X);
end Double_Me;
My_Int : Integer := 42;
begin
Double_Me(My_Int);
end Simple_Program; |
What's with "in" and "out"?
If a parameter is specified as "in", the parameter's value can be read. If "out" is specified, then the variable can be assigned to.
In the Double_It function, X can only be read. An attempt to assign a new value to X would result in the program not compiling and a very descriptive error message.
In the same way, if only "out" is specified, then any attempt to read the value of X will result in a similar compiler error. |
|
|