home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / info / c_tutorg / chap04.txt < prev    next >
Encoding:
Text File  |  1992-05-24  |  20.4 KB  |  413 lines

  1. This chapter discusses enhancements in the capabilities of
  2. functions that have been made to C++.  These changes make
  3. programming more convenient and permit the compiler to do further
  4. checking for errors.  A fair amount of time is also spent in this
  5. chapter teaching the modern form of function definition and
  6. prototyping.
  7.  
  8. Prototyping allows the compiler to do additional type checking for
  9. your function calls which can detect some programming errors.  The
  10. first two example programs in this chapter are designed to teach
  11. prototyping and what it will do for you.  Prototyping is a
  12. relatively new addition to C, so even some experienced C
  13. programmers are not familiar with it.  If you have experience with
  14. prototyping you can skip directly to the section named PASS BY
  15. REFERENCE on page 4-4 of this chapter.
  16.  
  17.  
  18. PROTOTYPES
  19. _________________________________________________________________
  20.  
  21. Examine the file named PROTYPE1.CPP for our      ================
  22. first look at a prototype and an illustration of @ref{PROTYPE1.CPP}
  23. how it is used.  The prototyping used in C++ is  ================
  24. no different than that used in ANSI-C.
  25. Actually, many C programmers take a rather dim
  26. view of prototyping and seem reluctant to use it, but with C++ it
  27. is considerably more important and is in much heavier use.  In
  28. fact, prototyping is required to be used in some situations in C++.
  29.  
  30. A prototype is a limited model of a more complete entity to come
  31. later.  In this case, the full function is the complete entity to
  32. come later and the prototype is illustrated in line 4.  The
  33. prototype gives a model of the interface to the function that can
  34. be used to check the calls to the function for the proper number
  35. of parameters and the correct types of parameters.  Each call to
  36. the function named do_stuff() must have exactly three parameters
  37. or the compiler will give an error message.  In addition to the
  38. correct number of parameters, the types must be compatible or the
  39. compiler will issue an error message.  Notice that when the
  40. compiler is working on lines 12 and 13, the type checking can be
  41. done based on the prototype in line 4 even though the function
  42. itself is not yet defined.  If the prototype is not given, the
  43. number of parameters will not be checked, nor will the types of the
  44. parameters be checked.  Even if you have the wrong number of
  45. parameters, you will get an apparently good compile and link, but
  46. the program may do some very strange things when it is executed.
  47.  
  48. To write the prototype, simply copy the header from the function
  49. to the beginning of the program and append a semicolon to the end
  50. as a signal to the compiler that this is not a function but a
  51. prototype.  The variable names given in the prototype are optional
  52. and act merely as comments to the program reader since they are
  53. completely ignored by the compiler.  You could replace the variable
  54. name wings in line 4 with your first name and there would be no
  55. difference in compilation.  Of course, the next person that had to
  56. read your program would be somewhat baffled with your choice of
  57. variable names.
  58.  
  59. In this case, the two function calls to this function, given in
  60. lines 12 and 13, are correct so no error will be listed during
  61. compilation.
  62.  
  63. Even though we wish to use the char type for eyes in the function,
  64. we wish to use it as a number rather than as a character.  The cast
  65. to int in line 20 is required to force the printout of the
  66. numerical value rather than an ASCII character.  The next example
  67. program is similar but without the cast to int.
  68.  
  69.  
  70. COMPATIBLE TYPES
  71. _________________________________________________________________
  72.  
  73. We mentioned compatible types earlier so we should review them just
  74. a bit in order to make our discussion of prototyping complete.
  75. Compatible types are any simple types that can be converted from
  76. one to another in a meaningful way.  For example, if you used an
  77. integer as the actual parameter and the function was expecting a
  78. float type as the formal parameter, the system would do the
  79. conversion automatically, without mentioning it to you.  This is
  80. also true of a float changing to a char, or a char changing to an
  81. int.  There are definite conversion rules which would be followed.
  82. These rules are given in great detail in section 3.2 of the draft
  83. of the ANSI-C standard and are also given on page 198 of the second
  84. edition of the K&R reference.
  85.  
  86. If we supplied a pointer to an integer as the actual parameter and
  87. expected an integer as the formal parameter in the function, the
  88. conversion would not be made because they are two entirely
  89. different kinds of values.  Likewise, a structure would not be
  90. converted automatically to a long float, an array, or even to a
  91. different kind of structure, they are all incompatible and cannot
  92. be converted in any meaningful manner.  The entire issue of type
  93. compatibility as discussed in chapter 2 of this tutorial applies
  94. equally well to the compatibility of types when calling a function.
  95. Likewise, the type specified as the return type, in this case void,
  96. must be compatible with the expected return type in the calling
  97. statement, or the compiler will issue a warning.
  98.  
  99.  
  100. HOW DOES PROTOTYPING WORK?
  101. _________________________________________________________________
  102.  
  103. This is your chance to try prototyping for yourself and see how
  104. well it works and what kinds of error messages you get when you do
  105. certain wrong things.  Change the actual parameters in line 12 to
  106. read (12.2, 13, 12345) and see what the compiler says about that
  107. change.  It will probably say nothing because they are all type
  108. compatible.  If you change it to read (12.0, 13), it will issue a
  109. warning or error because there are not enough arguments given.
  110. Likewise you should receive an error message if you change one of
  111. the parameters in line 13 to an address by putting an ampersand in
  112. front of one of the variable names.  Finally, change the first word
  113. in line 4 from void to int and see what kind of error message is
  114. given.  You will first be required to make the function header in
  115. line 16 agree with the prototype, then you will find that there is
  116. not a variable returned from the function.  You should have a good
  117. feeling that prototyping is doing something good for you after
  118. making these changes.
  119.  
  120. Be sure to compile and execute this program then make the changes
  121. recommended above, attempting to compile it after each change.
  122.  
  123.  
  124. A LITTLE MORE PROTOTYPING
  125. _________________________________________________________________
  126.  
  127. Examine the next example program named           ================
  128. PROTYPE2.CPP for a little more information on    @ref{PROTYPE2.CPP}
  129. prototyping.  This program is identical to the   ================
  130. last one except for a few small changes.  The
  131. variable names have been omitted from the
  132. prototype in line 4 merely as an illustration that they are
  133. interpreted as comments by the C++ compiler.  The function header
  134. is formatted differently to allow for a comment alongside each of
  135. the actual parameters.  This should make the function header a
  136. little more self explanatory.  However, you should remember that
  137. comments should not be used to replace careful selection of
  138. variable names.  In this particular case, the comments add
  139. essentially nothing to the clarity of the program.
  140.  
  141.  
  142. WHAT DOES PROTOTYPING COST?
  143. _________________________________________________________________
  144.  
  145. Prototyping is essentially free because it costs absolutely nothing
  146. concerning the run time size or speed of execution.  Prototyping
  147. is a compile time check and slows down the compile time a
  148. negligible amount because of the extra checking that the compiler
  149. must do.  If prototyping finds one error for you that you would
  150. have had to find with a debugger, it has more than paid for itself
  151. for use in an entire project.  I once spent 12 hours of debugging
  152. time to find that I forgot to pass the address of a variable to a
  153. function.  Prototyping would have found the error on the first
  154. compilation of this 2000 line program.
  155.  
  156. The only price you pay to use prototyping is the extra size of the
  157. source files because of the prototypes, and the extra time for the
  158. compiler to read the prototypes during the compilation process, but
  159. both costs are negligible.
  160.  
  161. Be sure to compile and execute this example program.  You will find
  162. that it is identical to the last example program.
  163.  
  164.  
  165. PASS BY REFERENCE
  166. _________________________________________________________________
  167.  
  168. Examine The file named PASSREF.CPP for an         ===============
  169. example of a pass by reference, a construct       @ref{PASSREF.CPP}
  170. which is not available in ANSI-C.  The reference  ===============
  171. variable was mentioned in chapter 1 and it was
  172. recommended there that you don't use it in the
  173. manner illustrated there.  This example program illustrates a
  174. situation where it can be used to your advantage.  The pass by
  175. reference allows the passing of a variable to a function and
  176. returning the changes made in the function to the main program.
  177. In ANSI-C the same effect can be seen when a pointer to a variable
  178. is passed to a function, but use of a reference variable is a
  179. little cleaner.
  180.  
  181. Observe the prototype in line 4 where the second variable has an
  182. ampersand in front of the variable name.  The ampersand instructs
  183. the compiler to treat this variable just like it were passed a
  184. pointer to the variable since the actual variable from the main
  185. program will be used in the function.  In the function itself, in
  186. lines 21 through 24, the variable in2 is used just like any other
  187. variable but we are using the variable passed to this function from
  188. the main program not a copy of it.  The other variable named in1
  189. is treated just like any other normal variable in ANSI-C.  In
  190. effect, the name in2 is a synonym for the variable named index in
  191. the main program.
  192.  
  193. If you prefer to omit the variable names in the prototypes, you
  194. would write the prototype as follows;
  195.  
  196.    void fiddle(int, int&);
  197.  
  198. If you are a Pascal programmer, you will recognize that the
  199. variable named in1 is treated just like a normal parameter in a
  200. Pascal call, a call by value.  The variable named in2 however, is
  201. treated like a variable with the reserved word VAR used in front
  202. of it usually referred to as a call by reference.  The reference
  203. variable is actually a self dereferencing pointer which refers to,
  204. or points to, the original value.
  205.  
  206. When you compile and execute this program, you will find that the
  207. first variable got changed in the function but was returned to its
  208. original value when we returned to the main program.  The second
  209. variable however, was changed in the function and the new value was
  210. reflected back into the variable in the main program which we can
  211. see when the values are listed on the monitor.
  212.  
  213.  
  214. DEFAULT PARAMETERS
  215. _________________________________________________________________
  216.  
  217. Examine the file named DEFAULT.CPP for an         ===============
  218. example of the use of default parameters in C++.  @ref{DEFAULT.CPP}
  219. This program really looks strange since it        ===============
  220. contains default values for some of the
  221. parameters in the prototype, but these default
  222. values are very useful as we will see shortly.
  223.  
  224. This prototype says that the first parameter named length must be
  225. given for each call of this function because a default value is not
  226. supplied.  The second parameter named width, however, is not
  227. required to be specified for each call, and if it is not specified,
  228. the value 2 will be used for the variable width within the
  229. function.  Likewise, the third parameter is optional, and if it is
  230. not specified, the value of 3 will be used for height within the
  231. function.
  232.  
  233. In line 11 of this program, all three parameters are specified so
  234. there is nothing unusual about this call from any other function
  235. call we have made.  Only two values are specified in line 12
  236. however, so we will use the default value for the third parameter
  237. and the system acts as if we called it with get_value(x, y, 3)
  238. since the default value for the third value is 3.  In line 13, we
  239. only specified one parameter which will be used for the first
  240. formal parameter, and the other two will be defaulted.  The system
  241. will act as if we had called the function with get_volume(x, 2, 3).
  242. Note that the output from these three lines is reversed.  This will
  243. be explained shortly.
  244.  
  245. There are a few rules which should be obvious but will be stated
  246. anyway.  Once a parameter is given a default value in the list of
  247. formal parameters, all of the remaining must have default values
  248. also.  It is not possible to leave a hole in the middle of the
  249. list, only the trailing values can be defaulted.  Of course, the
  250. defaulted values must be of the correct types or a compiler error
  251. will be issued.  The default values can be given in either the
  252. prototype or the function header, but not in both.  If they are
  253. given in both places, the compiler must not only use the default
  254. value, but it must carefully check to see that both values are
  255. identical.  This could further complicate an already very
  256. complicated problem, that of writing a C++ compiler.
  257.  
  258. As a matter of style, it is highly recommended that the default
  259. values be given in the prototype rather than in the function.  The
  260. reason will be obvious when we begin using object oriented
  261. programming techniques.
  262.  
  263.  
  264. WHY IS THE OUTPUT SCRAMBLED?
  265. _________________________________________________________________
  266.  
  267. When the compiler finds a cout statement, the complete line of code
  268. is initially scanned from right to left to evaluate any functions,
  269. then the data is output field by field from left to right.
  270. Therefore in line 11, get_value() is evaluated with its internal
  271. output displayed first.  Then the fields of the cout are displayed
  272. from left to right with "Some box data is" displayed next.
  273. Finally, the result of the return from get_value() is output in int
  274. format, the type of the returned value.  The end result is that the
  275. output is not in the expected order when lines 11 through 13 are
  276. executed.  (The output is not what you would intuitively expect to
  277. happen so appears to be a deficiency in the language.  A call to
  278. Borland International, the writers of Turbo C++ and Borland C++,
  279. verified that this is operating correctly.)
  280.  
  281. Lines 15 through 18 are similar to any two of the lines of code in
  282. lines 11 through 13, but are each separated into two lines so the
  283. output is in the expected order.
  284.  
  285. Be sure to compile and execute DEFAULT.CPP after you understand it.
  286. Note that the funny output order will appear again later in this
  287. tutorial.
  288.  
  289.  
  290. VARIABLE NUMBER OF ARGUMENTS
  291. _________________________________________________________________
  292.  
  293. Examine the program named VARARGS.CPP for an      ===============
  294. illustration of the use of a variable number of   @ref{VARARGS.CPP}
  295. arguments in a function call.                     ===============
  296.  
  297. We have gone to a lot of trouble to get the
  298. compiler to help us by carefully checking how many parameters we
  299. use in the function calls and checking the types of the parameters.
  300. On rare occasion, we may wish to write a function that uses a
  301. variable number of parameters.  The printf() function is a good
  302. example of this.  ANSI-C has a series of three macros available in
  303. the "stdarg.h" header file to allow the use of a variable number
  304. of arguments.  These are available for use with C++ also, but we
  305. need a way to eliminate the strong type checking that is done with
  306. all C++ functions.  The three dots illustrated in line 6 will do
  307. this for us.  This prototype says that a single argument of type
  308. int is required as the first parameter, then no further type
  309. checking will be done by the compiler.
  310.  
  311. You will note that the main program consists of three calls to the
  312. function, each with a different number of parameters, and the
  313. system does not balk at the differences in the function calls.  In
  314. fact, you could put as many different types as you desire in the
  315. calls.  As long as the first one is an int type variable, the
  316. system will do its best to compile and run it for you.  Of course
  317. the compiler is ignoring all type checking beyond the first
  318. parameter so it is up to you to make sure you use the correct
  319. parameter types in this call.
  320.  
  321. In this case the first parameter gives the system the number of
  322. additional parameters to look for and handle.  In this simple
  323. program, we simply display the numbers on the monitor to illustrate
  324. that they really did get handled properly.
  325.  
  326. Of course, you realize that using a variable number of arguments
  327. in a function call can lead to very obscure code and should be used
  328. very little in a production program, but the capability exists if
  329. you need it.  Be sure to compile and execute this program.
  330.  
  331.  
  332. FUNCTION NAME OVERLOADING
  333. _________________________________________________________________
  334.  
  335. Examine the file named OVERLOAD.CPP for an       ================
  336. example of a program with the function names     @ref{OVERLOAD.CPP}
  337. overloaded.  This is not possible in ANSI-C, but ================
  338. is perfectly legal and in fact used quite
  339. regularly in C++.  At first this will seem a bit
  340. strange, but it is one of the keystones of object oriented
  341. programming.  You will see its utility and purpose very clearly in
  342. later chapters of this tutorial.
  343.  
  344. You will notice in this example program that there are three
  345. functions, in addition to the main function, and all three have the
  346. same name.  Your first question is likely to be, "Which function
  347. do you call when you call do_stuff()?"  That is a valid question
  348. and the answer is, the function that has the correct number of
  349. formal parameters of the correct types.  If do_stuff() is called
  350. with an integer value or variable as its actual parameter, the
  351. function beginning in line 23 will be called and executed.  If the
  352. single actual parameter is of type float, the function beginning
  353. in line 28 will be called, and if two floats are specified, the
  354. function beginning in line 34 will be called.
  355.  
  356. It should be noted that the return type is not used to determine
  357. which function will be called.  Only the formal parameters are used
  358. to determine which overloaded function will be called.
  359.  
  360.  
  361. The keyword overload used in line 4 tells the system that you
  362. really do intend to overload the name do_stuff, and the overloading
  363. is not merely an oversight.  This is only required in C++ version
  364. 1.2.  C++ version 2.0 and greater do not require the keyword
  365. overload but allows it to be used optionally in order to allow the
  366. existing body of C++ code to be compatible with newer compilers.
  367. It is not necessary to use this keyword because, when overloading
  368. is used in C++, it is generally used in a context in which it is
  369. obvious that the function name is overloaded.
  370.  
  371. The actual selection of which function to actually call is done at
  372. compile time, not at execution time so the program is not slowed
  373. down.  If each of the overloaded function names were changed to
  374. different names, each being unique, there would be no difference
  375. in execution size or speed of the resulting program.
  376.  
  377. Overloading of function names may seem very strange to you, and it
  378. is strange if you are used to the rules of K&R or ANSI-C
  379. programming.  As you gain experience with C++, you will feel very
  380. comfortable with this and you will use it a lot in your C++
  381. programming.
  382.  
  383. Note the use of the keyword const used in some of the function
  384. prototypes and headers.  Once again, this prevents the programmer
  385. from accidentally changing the formal parameter within the
  386. function.  In a function as short as these, there is no real
  387. problem with an accidental assignment.  In a real function that you
  388. occasionally modify, you could easily forget the original intention
  389. of the use of a value and attempt to change it during an extended
  390. debugging session.
  391.  
  392.  
  393. PROGRAMMING EXERCISES
  394. _________________________________________________________________
  395.  
  396. 1.   Change the type of wings in the prototype of PROTYPE1.CPP to
  397.      float so that it disagrees with the function definition to see
  398.      if you get a compilation error.
  399.  
  400. 2.   Change the function definition in PROTYPE1.CPP to agree with
  401.      the changed prototype.  Compile and execute the program
  402.      without changing the calls in lines 12 and 13.  Explain the
  403.      results.
  404.  
  405. 3.   In DEFAULT.CPP, remove the default value from the prototype
  406.      for height only to see what kind of compiler error you get.
  407.      Only the last values of the list can be defaulted.
  408.  
  409. 4.   In OVERLOAD.CPP, change the names of the three functions so
  410.      that each is a unique name and compare the size of the
  411.      resulting executable file with that given for the present
  412.      program.
  413.