* Re: Procedure vs function
2014-09-06 2:19 Procedure vs function Stribor40
@ 2014-09-06 5:44 ` Niklas Holsti
2014-09-06 6:25 ` Jeffrey Carter
0 siblings, 1 reply; 3+ messages in thread
From: Niklas Holsti @ 2014-09-06 5:44 UTC (permalink / raw)
On 14-09-06 05:19 , Stribor40 wrote:
> Would anyone please try to explain difference between procedure and
> function. Some online material describes procedure as of series
> of declaration and algoritmic code and function is something that
> returns data type. Does this mean that procedure can be within
> the scope of function perhaps body of the procedure inside the
> body of function?
>
> Any info or simple example would be appreciated
See http://en.wikibooks.org/wiki/Ada_Programming/Subprograms.
In a nutshell: the only difference between a function subprogram and a
procedure subprogram is that a function call returns a value, from a
"return <expression>" statement inside the function, and therefore a
function call can (and must) be used as part of an expression, not as a
stand-alone statement.
A procedure call does not return a value and therefore can be used only
as a statement of its own, not within an expression. The effect of the
procedure call is to assign values to its "out" and "in out" parameters
and perhaps to other variables to which the procedure has access.
Function calls can also have such effects, in addition to returning a value.
Example:
function Square (X : Float) return Float
is
begin
return X * X;
end Square;
Then it is possible to write the expression Square(A) + Square(B), where
A and B are some Float expressions, and the result is the sum of the
squares of A and B.
The same could be written as a procedure:
procedure Compute_Square (X : in Float; Y : out Float)
is
begin
Y := X * X;
end Compute_Square;
Now, to compute the sum of the squares of A and B, some auxiliary
variables Sq_A, Sq_B and two statements are needed:
Compute_Square (X => A, Y => Sq_A);
Compute_Square (X => B, Y => Sq_B);
and then you can write Sq_A + Sq_B for the sum of the squares of A and B.
Typically, procedures are used for computations that return several
results (in the "out" and "in out" parameters) or have significant side
effects on other data. Functions are typically used to compute a single
new value from the function's parameters, where the computation has no
significant side effects. But these are just design conventions.
Subprograms of any kind can be nested within other subprograms, whether
the subprograms are functions or procedures.
--
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
. @ .
^ permalink raw reply [flat|nested] 3+ messages in thread