home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / tutorial / cpptutor / text / chap04.txt < prev    next >
Encoding:
Text File  |  1994-05-15  |  22.7 KB  |  464 lines

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