Computer Science Canada [Ada-tut] Functions and procedures |
Author: | wtd [ 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.
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.
Now let's create a procedure which sets My_Int to 42.
And calling the Set_My_Int procedure, which calls the Forty_Two function is as simple as:
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.
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. |