18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

70 Procedures and functions<br />

function Sum( P1:<strong>in</strong> Integer := 0;<br />

P2:<strong>in</strong> Integer := 0;<br />

P3:<strong>in</strong> Integer := 0;<br />

P4:<strong>in</strong> Integer := 0 ) return Integer is<br />

beg<strong>in</strong><br />

return P1 + P2 + P3 + P4;<br />

end Sum;<br />

with <strong>Ada</strong>.Text_Io, <strong>Ada</strong>.Integer_Text_io;<br />

use <strong>Ada</strong>.Text_Io, <strong>Ada</strong>.Integer_Text_io;<br />

procedure Answer_Is( N:<strong>in</strong> Integer;<br />

Message:<strong>in</strong> Boolean := True ) is<br />

beg<strong>in</strong><br />

if Message then Put("The answer = "); end if;<br />

Put( N, Width=>1 );<br />

if Message then New_L<strong>in</strong>e; end if;<br />

end Answer_Is;<br />

Note: Formal parameters to the function Sum are given a default value of 0, if a value has not been supplied<br />

by a caller of the function.<br />

Any actual parameter to a function or procedure may be specified either by position or by name. For example, the<br />

second formal parameter to the function Answer_Is can be specified <strong>in</strong> the follow<strong>in</strong>g ways:<br />

Answer_Is( 27, True ); -- By position<br />

Answer_Is( 27, Message => False ); -- By name<br />

Note:<br />

If a parameter is specified by name, then all subsequent parameters must be specified by name.<br />

5.9.1 Putt<strong>in</strong>g it all together<br />

The procedures sum and Answer_Is can be used <strong>in</strong> a program as follows:<br />

with Sum, Answer_Is;<br />

procedure Ma<strong>in</strong> is<br />

beg<strong>in</strong><br />

Answer_Is( Sum );<br />

Answer_Is( Sum( 1, 2 ) );<br />

Answer_Is( Sum( 1, 2, 3 ) );<br />

Answer_Is( Sum( 1, 2, 3, 4 ), Message => False );<br />

New_L<strong>in</strong>e;<br />

end Ma<strong>in</strong>;<br />

The code that is actually compiled for the procedure Ma<strong>in</strong> above is:<br />

with Sum, Answer_Is;<br />

procedure Ma<strong>in</strong> is<br />

beg<strong>in</strong><br />

Answer_Is( Sum( 0, 0, 0, 0 ), True );<br />

Answer_Is( Sum( 1, 2, 0, 0 ), True );<br />

Answer_Is( Sum( 1, 2, 3, 0 ), True );<br />

Answer_Is( Sum( 1, 2, 3, 4 ), False );<br />

New_L<strong>in</strong>e;<br />

end Ma<strong>in</strong>;<br />

which is more complex for the writer to construct and for a ma<strong>in</strong>ta<strong>in</strong>er to follow.<br />

© M A Smith - May not be reproduced without permission

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!