home *** CD-ROM | disk | FTP | other *** search
/ Chip 1995 March / CHIP3.mdf / programm / prog1 / chap08.txt < prev    next >
Encoding:
Text File  |  1991-07-01  |  22.8 KB  |  529 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 8
  5.                                                       SUBPROGRAMS
  6.  
  7.  
  8. LET'S LOOK AT A PROCEDURE
  9. _________________________________________________________________
  10.  
  11. Ada was designed to be very modular, and we come  ===============
  12. to the point where we will study the first and      PROCED1.ADA
  13. simplest form of modularization, the procedure.   ===============
  14. If you examine the program named PROCED1.ADA,
  15. you will have your first example of a procedure.
  16. Some languages call this kind of subprogram a subroutine, others
  17. a function, but Ada calls it a procedure.
  18.  
  19.  
  20. THE PROCEDURE IS LIKE THE MAIN PROGRAM
  21. _________________________________________________________________
  22.  
  23. Beginning with the executable part of the main program, we have two
  24. executable statements in lines 14 and 15, each calling a procedure
  25. to write a line, if the name has any meaning.  As always, the two
  26. statements are executed in succession, and each statement is a
  27. procedure call to which we would like to transfer control.  The
  28. procedure itself is defined in lines 7 through 11, and a close
  29. inspection will reveal that the structure of the procedure is very
  30. similar to the structure for the main program.  It is in fact,
  31. identical to the main program, and just as we begin executing the
  32. main program by mentioning its name, we begin executing the
  33. procedure by mentioning its name.  The procedure has a declarative
  34. part, which is empty in this case, and an executable part which
  35. says to display a line of text and return the cursor to the
  36. beginning of the next line.
  37.  
  38. When execution reaches the end statement of the procedure, the
  39. procedure is complete and control returns to the next successive
  40. statement in the calling program.
  41.  
  42. Everything we have said about the main program, which is actually
  43. a procedure, is true for the procedure.  Thus we can define new
  44. types, declare variables and constants, and even define additional
  45. procedures in the declarative part of this procedure.  Likewise,
  46. we can call other procedures, and do assignments and compares in
  47. the executable part of the procedure.
  48.  
  49.  
  50.  
  51. ORDER OF DECLARATIONS
  52. _________________________________________________________________
  53.  
  54. The procedure must come after all type, constant, and variable
  55. declarations.  Ada forces you to arrange your program such that all
  56. of the smaller declarations must come first, followed by the larger
  57.  
  58.                                                          Page 8-1
  59.  
  60.                                           Chapter 8 - Subprograms
  61.  
  62. ones.  This is so that the small declarations don't get lost among
  63. the bigger ones.
  64.  
  65. The embedded procedure has all of the flexibility and requirements
  66. as those defined for the main procedure.  We will give further
  67. examples of each of these points in the next few example programs.
  68. At this time, compile and run this program, and make sure you
  69. understand its operation completely.
  70.  
  71.  
  72. THREE PROCEDURES
  73. _________________________________________________________________
  74.  
  75. Examine the program named PROCED2.ADA, and you    ===============
  76. will see three procedures in the declarative        PROCED2.ADA
  77. part of this program.  Jumping ahead to the main  ===============
  78. program, beginning in line 33, you will see that
  79. the program will write a header, write and
  80. increment something 7 times, then write an ending statement.
  81. Notice how the use of descriptive procedure names resulted in our
  82. understanding of what the program will do without looking at the
  83. procedures themselves.  The names are long, and a bit tedious to
  84. type in, but since Ada was designed to be a language that would be
  85. written once and read many times, the extra time will pay off when
  86. the source code is studied by several persons in the future.
  87.  
  88.  
  89. WHAT IS A GLOBAL VARIABLE?
  90. _________________________________________________________________
  91.  
  92. The variable named Counter, defined in line 10, is a global
  93. variable because it is defined prior to any procedure.  It is
  94. therefore available for use by any of these procedures and it is,
  95. in fact, used by two of them.  In line 14, the variable Counter is
  96. assigned the value of 1 when the procedure named Write_A_Header is
  97. called.  Each time Write_And_Increment is called, the current value
  98. of Counter is written to the display, along with a message, and the
  99. value is incremented.  Note carefully that the procedures are not
  100. executed in the order they are because of their relative order, but
  101. because the main program calls them in that order.  The program
  102. would work exactly the same way if you moved the first procedure,
  103. in its entirety of course, after the procedure
  104. Write_An_Ending_Statement.  The order of execution is controlled
  105. by the order of calls, not the physical order of the procedures.
  106.  
  107.  
  108. WHY DO PROCEDURES GO IN THE DECLARATIVE PART?
  109. _________________________________________________________________
  110.  
  111. The declarative part of the program is where we define entities for
  112. use within the executable part.  The procedures are actually
  113. definitions of how to do something, so they are right where they
  114. belong, but they must come after the smaller declarations.  To
  115. reiterate a rule stated earlier, the variable must be declared
  116.  
  117.                                                          Page 8-2
  118.  
  119.                                           Chapter 8 - Subprograms
  120.  
  121. prior to the procedure declarations so that it does not get lost
  122. among the procedures.  Compile and run this program and be sure you
  123. understand the output.
  124.  
  125.  
  126. A PROCEDURE WITH PARAMETERS
  127. _________________________________________________________________
  128.  
  129. Examine the file named PROCED3.ADA and you will   ===============
  130. find a procedure that requires some data to be      PROCED3.ADA
  131. supplied to it each time it is called.  Three     ===============
  132. variables are defined as type INTEGER and used
  133. in the procedure call in line 28.  We will
  134. ignore the strange looking constructs in lines 12 through 15 for
  135. a couple of paragraphs.  The procedure header, beginning in line
  136. 18, states that it is expecting three inputs, and each must be of
  137. type INTEGER, so we are compatible so far.  When the procedure is
  138. called, the value of the first variable, which is named Dogs in
  139. this case, is taken to the procedure, where the procedure prefers
  140. to refer to it by the name Variety1.  In like manner, the value of
  141. Cats is given to the procedure, and is called Variety2.  The
  142. variable named Animals is referred to by the name Total in the
  143. procedure.  The procedure is now ready to do some meaningful work
  144. with these variables, but is somewhat limited in what it can do to
  145. them because of the mode field of the procedure header.
  146.  
  147.  
  148. THE MODE OF A PARAMETER
  149. _________________________________________________________________
  150.  
  151. The formal parameter, as it is called in the procedure header,
  152. named Variety1, is of mode in which means that it is an input
  153. parameter, and therefore cannot be changed within the procedure.
  154. Variety1, along with Variety2 for the same reason, is a constant
  155. within the procedure, and any attempt to assign a value to it will
  156. result in a compile error.  The formal parameter named Total,
  157. however, is of mode out and can therefore have a new value assigned
  158. to it within the procedure.  It is illegal to attempt to read this
  159. variable within the procedure, because it is of output mode only.
  160. If it were defined as being of mode in out, it could be both read
  161. from and written to.  If no mode is given, the system will use mode
  162. in as a default.
  163.  
  164.  
  165. PARAMETER MODE SELECTION
  166. _________________________________________________________________
  167.  
  168. All variables could be defined as mode in out and there would be
  169. no problems, since there would be maximum flexibility, or so it
  170. would seem.  There is another rule that must be considered, and
  171. that rule says that every parameter that is of mode out or in out
  172. must be called with a variable as the actual parameter in the
  173. calling program.  A variable of mode in can use a constant or a
  174. variable for the actual parameter in the calling program.  We have
  175.  
  176.                                                          Page 8-3
  177.  
  178.                                           Chapter 8 - Subprograms
  179.  
  180. been using the New_Line procedure with a constant in it, such as
  181. New_Line(2), and if it had been defined with the formal parameter
  182. of mode in out, we would have had to define a variable, assign the
  183. value 2 to it, and use the variable in the call.  This would have
  184. made the procedure a bit more difficult to use, and in fact,
  185. somewhat awkward.  For this reason, the formal parameter in
  186. New_Line was defined using mode in.  You should choose the mode of
  187. the formal parameters very carefully.
  188.  
  189. The three formal parameters are available for use in the procedure,
  190. once they are defined as illustrated, just as if they had been
  191. defined in the declarative portion of the procedure.  They are not
  192. available to any other procedure or the main program, because they
  193. are defined locally for the procedure.  When used however, their
  194. use must be consistent with the defined mode for each.
  195.  
  196.  
  197. SOME GLOBAL VARIABLES
  198. _________________________________________________________________
  199.  
  200. The three variables declared in line 10 can be referred to in the
  201. procedure as well as in the main program.  Because it is possible
  202. to refer to them in the procedure, they can be changed directly
  203. within the procedure.  The variable Animals can also be modified
  204. when control returns to the main program because it is declared of
  205. out mode in the procedure header.  This possibility can lead to
  206. some rather unusual results.  You should spend some time thinking
  207. about what this really means.
  208.  
  209.  
  210. THE PROCEDURE SPECIFICATION
  211. _________________________________________________________________
  212.  
  213. Lines 13, 14, and 15, give an example of a procedure specification.
  214. This is an incomplete procedure declaration that you will find
  215. useful when you begin writing larger programs.  The procedure
  216. specification can be included for any procedure, if desired, and
  217. it describes the external interface to the procedure without
  218. declaring what the procedure actually does.  The Pascal programmer
  219. will recognize this as being very similar to the forward
  220. declaration.  More will be said about this topic later.  Note that
  221. the procedure specification is not required in this case, it is
  222. only included as an illustration.
  223.  
  224. Compile and run this program after you understand the simple
  225. addition and assignment that is done for purposes of illustration.
  226.  
  227.  
  228. PROCEDURES CALLING OTHER PROCEDURES
  229. _________________________________________________________________
  230.  
  231. The example program CALLING.ADA contains examples of a procedure
  232. calling another procedure, which is perfectly legal if the called
  233. procedure is within the scope of the calling procedure.  Much more
  234.  
  235.                                                          Page 8-4
  236.  
  237.                                           Chapter 8 - Subprograms
  238.  
  239. will be said about scope later in this tutorial.  ===============
  240. The only rule that will be mentioned here is        CALLING.ADA
  241. that the procedure must be defined prior to a     ===============
  242. call to it.  You should have no trouble
  243. understanding this program, and when you do, you
  244. should compile and execute it.
  245.  
  246.  
  247. HOW DO WE NEST PROCEDURES?
  248. _________________________________________________________________
  249.  
  250. Examine the program named NESTING.ADA for         ===============
  251. examples of nested procedures.  We mentioned        NESTING.ADA
  252. earlier that it was possible to embed a           ===============
  253. procedure within the declarative part of any
  254. other procedure.  This is illustrated in lines
  255. 10 through 21 where the procedure Second_Layer is embedded within
  256. the procedure Triple.  In addition, the procedure Second_Layer has
  257. the procedure Bottom_Layer embedded within its declarative part in
  258. lines 12 through 15.  Such nesting can continue indefinitely,
  259. because there is no limit to the depth of nesting allowed in Ada.
  260.  
  261.  
  262. VISIBILITY OF PROCEDURES
  263. _________________________________________________________________
  264.  
  265. There is a limit on visibility of procedures.  Any procedure is
  266. visible, and can therefore be called, if it is within the top level
  267. of the declarative part of the calling procedure.  Any procedure
  268. is also visible if it is prior to, on the same level, and within
  269. the same declarative part as the calling point.  Finally, any
  270. procedure can be called if it is prior to, on the same level, and
  271. within the same declarative part as any subprogram within which the
  272. calling point in nested.  In simpler words, a procedure is visible
  273. in three cases.  First, if it is within the declarative part of the
  274. calling procedure.  The second case is if it is a peer (on the same
  275. level within a parent subprogram) or thirdly, if it is a peer of
  276. any parent.
  277.  
  278. The procedure named Triple can therefore call Second_Layer, but not
  279. Bottom_Layer, since it is at a lower level and is not visible.  The
  280. main program, according to these rules, is only allowed to call
  281. Triple, because the other two procedures are nested too deeply for
  282. a direct call.  Be sure to compile and run this program and study
  283. the results.
  284.  
  285.  
  286. ADA FUNCTIONS
  287. _________________________________________________________________
  288.  
  289. The program named FUNCT.ADA has two examples of Ada functions.  A
  290. function differs from a procedure in only two ways.  A function
  291. returns a single value which is used in the place of its call, and
  292. all formal parameters of a function must be of type in, with no
  293.  
  294.                                                          Page 8-5
  295.  
  296.                                           Chapter 8 - Subprograms
  297.  
  298. other mode permitted.  In the program under       ===============
  299. consideration, two functions are illustrated,        FUNCT.ADA
  300. one beginning in line 16, and the other           ===============
  301. beginning in line 21.  Note that each begins
  302. with the reserved word function.
  303.  
  304.  
  305. A FUNCTION SPECIFICATION
  306. _________________________________________________________________
  307.  
  308. In a manner similar to that defined for a procedure we can define
  309. a function specification that gives the interface of the function
  310. to the outside world.  You will find the function specification
  311. useful later in your Ada programming efforts.  It is similar to the
  312. Pascal forward declaration.  Note once again, that the function
  313. specification is not required, it is only given here as an
  314. illustration.
  315.  
  316. The function named Square requires one argument which it prefers
  317. to call Val, and which must be of type INTEGER.  It returns a value
  318. to the main program which will be of type INTEGER because that is
  319. the type given between the reserved words return and is in the
  320. function body.
  321.  
  322. A function must return a value, and the value is returned by
  323. following the reserved word return with the value to be returned.
  324. This return must be done in the executable part of the program, as
  325. illustrated in line 18.  It is an error to fail to execute a return
  326. statement and fall through the end of a function.  Such a runtime
  327. error will be reported by raising the exception Program_Error,
  328. which will be explained later in this tutorial.
  329.  
  330.  
  331. CAN YOU RETURN FROM A PROCEDURE?
  332. _________________________________________________________________
  333.  
  334. It would be well to point out that you can return from a procedure
  335. by using the return statement also, but no value can be given since
  336. a procedure does not return a value in the same manner as a
  337. function.  The return statement can be anyplace in the procedure
  338. or function and there can be multiple returns if the logic dictates
  339. the possibility of returning from several different places.
  340.  
  341.  
  342. A VALUE IS SUBSTITUTED FOR THE FUNCTION CALL
  343. _________________________________________________________________
  344.  
  345. Examining the executable part of the program, we find that the
  346. variable Twelve is initialized to the value of 12, and this
  347. variable is used in line 28 as the argument for the function
  348. Square.  This causes Square to be called, where the value of 12 is
  349. squared and the result is returned as 144.  It is as if the
  350. resulting value of 144 replaces the function call Square(Twelve)
  351. in the Put procedure call, and the value of 144 is displayed.
  352.  
  353.                                                          Page 8-6
  354.  
  355.                                           Chapter 8 - Subprograms
  356.  
  357. Continuing on to line 30, the variable Twelve, which is still
  358. assigned the value of 12, and the constant 12, are given to the
  359. function Sum_Of_Numbers which returns the sum of 24.  This value
  360. is assigned to the variable named Sum where it is stored for use
  361. in line 32.
  362.  
  363. A function can be defined with no input parameters, in which case,
  364. the function is called with no parameters.  Such a case would be
  365. useful for a random number generator where the call could be X :=
  366. Random; assuming a new random number is returned each time the
  367. function is called.  Compile and execute this program and study the
  368. output generated.
  369.  
  370.  
  371. ANOTHER NOTE ABOUT THE DERIVED TYPE
  372. _________________________________________________________________
  373.  
  374. As mentioned in chapter 6, a derived type with INTEGER as parent
  375. could be declared in line 14, and the derived type would inherit
  376. all operations available with INTEGER, including the ability to be
  377. used as the formal parameter for the function Square.  This means
  378. that the function Square could be called with a variable of either
  379. of the two types.  In order to do this, it is necessary to use a
  380. function specification so that the function body will follow the
  381. derived type declaration.  Ada requires all smaller declarations
  382. to be made before subprogram bodies, so they do not get lost among
  383. the larger definitions.
  384.  
  385.  
  386. A FULLER EXAMPLE
  387. _________________________________________________________________
  388.  
  389. Examine the program named ODDSQRE.ADA which is    ===============
  390. a rather odd program that computes the square of    ODDSQRE.ADA
  391. an integer type variable, but maintains the sign  ===============
  392. of the variable.  In this program, the odd
  393. square of 3 is 9, and the odd square of -3 is
  394. -9.  Its real purpose is to illustrate several procedures and a
  395. function interacting.
  396.  
  397. The main program named OddSqre has a function and a procedure
  398. nested within its declarative part, both of which have parameters
  399. passed.  The nested procedure named Square_And_Keep_Sign has
  400. another procedure nested within its declarative part, named
  401. Do_A_Negative_Number which calls the function declared at the next
  402. higher level.
  403.  
  404. This program is a terrible example of how to solve the problem at
  405. hand but is an excellent example of several interacting
  406. subprograms, and it would be profitable for you to spend enough
  407. time with it to thoroughly understand it.
  408.  
  409.  
  410.  
  411.  
  412.                                                          Page 8-7
  413.  
  414.                                           Chapter 8 - Subprograms
  415.  
  416. COMMENTS ON ODDSQRE.ADA
  417. _________________________________________________________________
  418.  
  419. This program illustrates some of the options that are purely
  420. programming taste.  The first option is illustrated in line 24,
  421. where we could have chosen to use the construct Number_To_Square**2
  422. instead of the simple multiplication.  Either form is correct and
  423. the one to be used should reflect the nature of the problem at
  424. hand.  The second option is the fact that three returns were
  425. included in lines 39, 42, and 45, when a single return could have
  426. been used following the end of the if statement.  This was done to
  427. illustrate multiple returns in use.  In some cases, the logic of
  428. the program is much clearer to use several returns instead of only
  429. one.  More than anything else, it is a matter of personal taste.
  430. Be sure to compile and execute this program.
  431.  
  432.  
  433. OVERLOADING
  434. _________________________________________________________________
  435.  
  436. We have casually mentioned overloading earlier   ================
  437. in this tutorial and it is now time to get a       OVERLOAD.ADA
  438. good example of what overloading is by examining ================
  439. the program named OVERLOAD.ADA.  This program
  440. includes two functions and two procedures and
  441. all four of these subprograms have the same name.
  442.  
  443. The Ada system has the ability to discern which subprogram you wish
  444. to use by the types included in the actual parameter list and the
  445. type of the return.  In line 48, we make a call to a function with
  446. a 2, which is an integer type constant, and we assign the returned
  447. value to an INTEGER type variable.  The system will look for a
  448. function named Raise_To_Power with a single integer class formal
  449. parameter and an INTEGER type return which it finds in lines 14
  450. through 18, so it executes this function.  The actual searching
  451. will be done at compile time so the efficiency is not degraded in
  452. any way by the overloaded names.
  453.  
  454. If you continue studying this program you will see how the system
  455. can find the correct subprogram by comparing types used as formal
  456. parameters, and the type returned.  Using the same name for several
  457. uses is referred to as overloading the subprogram names and is an
  458. important concept in the Ada language.
  459.  
  460.  
  461. OVERLOADING CAN CAUSE YOU PROBLEMS
  462. _________________________________________________________________
  463.  
  464. If we made an error in this example program, by inadvertently
  465. omitting the decimal point in line 50, and assigning the result to
  466. an integer type variable, the system would simply use the wrong
  467. function and generate invalid data for us.  An even worse problem
  468. could be found if we had a function that used an INTEGER for input
  469. and a FLOAT for output, because only one small error could cause
  470.  
  471.                                                          Page 8-8
  472.  
  473.                                           Chapter 8 - Subprograms
  474.  
  475. erroneous results.  Because of this, it would be to your advantage
  476. to use different subprogram names for different operations, unless
  477. using the same names results in clear code.
  478.  
  479. In the case of the text output procedures which we have been using,
  480. it makes a lot of sense to overload the output subprograms to avoid
  481. confusion.  The name Put is used for outputting strings, integers,
  482. enumerated types, etc, and we are not confused.  Overloading can
  483. be an advantage in certain cases but should not be abused just
  484. because it is available.  Be sure to compile and execute this
  485. program.
  486.  
  487.  
  488. PROGRAMMING EXERCISES
  489. _________________________________________________________________
  490.  
  491. 1.   Rewrite TEMPCONV.ADA to do the temperature conversion in a
  492.      procedure.
  493.  
  494. 2.   Rewrite TEMPCONV.ADA to do the temperature conversion in a
  495.      function.
  496.  
  497. 3.   As mentioned in the text, add a function to the program
  498.      OVERLOAD.ADA that uses an INTEGER for input and returns a
  499.      FLOAT type result.  Remove the decimal point from line 50 to
  500.      see that the new function is called when we really intended
  501.      to call the procedure with the floating point number.
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.                                                          Page 8-9