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

  1.  
  2.  
  3.  
  4.                                                         Chapter 1
  5.                                                     SIMPLE THINGS
  6.  
  7. As we begin the study of C++ and object oriented programming, a 
  8. few comments are in order to help you get started.  Since the 
  9. field of object oriented programming is probably new to you, you 
  10. will find that there is a significant amount of new terminology 
  11. for you to grasp.  This is true of any new endeavor and you 
  12. should be warned not to be intimidated by all of the new 
  13. concepts.  We will add a few new topics in each chapter and you 
  14. will slowly grasp the entire language.
  15.  
  16. Chapters one through four of this tutorial will concentrate on 
  17. the non object oriented additions to C++.  We will not begin the 
  18. discussion of any object oriented programming techniques until 
  19. chapter five.
  20.  
  21.  
  22. EVEN COMMENTS ARE IMPROVED IN C++
  23. -----------------------------------------------------------------
  24. Examine the file named CONCOM.CPP for an       ==================
  25. example of several new things in C++.  We          CONCOM.CPP
  26. will take the new constructs one at a time     ==================
  27. beginning with the comments. A C++ comment 
  28. begins with the double slash "//", starts anywhere on a line, and 
  29. runs to the end of that line where it is automatically terminated.  
  30. The old method of comment definition used with ANSI-C can also be 
  31. used with C++ as illustrated in lines 11 through 14, among other 
  32. places in this program.  The new method is the preferred method 
  33. of comment definition because it is impossible to inadvertently 
  34. comment out several lines of code.  This can be done by 
  35. forgetting to include the end of comment notation when using the 
  36. older C method of comment notation.  Good programming practice 
  37. would be to use the new method for all comments and reserve the 
  38. old method for use in commenting out a section of code during 
  39. debugging since the two methods can be nested.
  40.  
  41. It would be well to caution you at this point however, that you 
  42. should not use comments when the same sense of program definition 
  43. can be obtained by using meaningful names for variables, 
  44. constants, and functions.  The careful selection of variable and 
  45. function names can make nearly any code self documenting and you 
  46. should strive to achieve this in your code.
  47.  
  48.  
  49. THE KEYWORDS const AND volatile
  50. -----------------------------------------------------------------
  51. There are two new keywords used in lines 9 through 11 which were 
  52. not part of the original K&R definition of C, but are part of the 
  53. ANSI-C standard.  The keyword const is used to define a constant.  
  54. In line 9 the constant is of type int, it is named START, and is 
  55. initialized to the value 3.  The compiler will not allow you to 
  56.  
  57.                                                          Page 1-1
  58.  
  59.                                         Chapter 1 - Simple Things
  60.  
  61. accidentally or purposefully change the value of START because it 
  62. has been declared a constant.  If you had a variable named STARTS 
  63. in this program, the system would not allow you to slightly 
  64. misspell STARTS as START and accidentally change it.  The 
  65. compiler would give you an error message so you could fix the 
  66. error.  Since it is not permissible to change the value of a 
  67. constant, it is imperative that you initialize it when it is 
  68. declared so it will have a useful value.  The compiler does not 
  69. require you to initialize it however, and will not issue an error 
  70. message if you do not.
  71.  
  72. You will note that the keyword const is also used in the function 
  73. header in line 21 to indicate that the formal parameter named 
  74. data_value is a constant throughout the function.  Any attempt to 
  75. assign a new value to this variable will result in a compile 
  76. error.  This is a small thing you can add to your programs to 
  77. improve the compilers ability to detect errors for you.
  78.  
  79. The keyword volatile is also part of the ANSI-C standard but was 
  80. not included in the original K&R definition of C.  Even though 
  81. the value of a volatile variable can be changed by you, the 
  82. programmer, there may be another mechanism by which the value 
  83. could be changed, such as by a hardware interrupt timer causing 
  84. the value to be incremented.  The compiler needs to know that 
  85. this value may be changed by some external force when it 
  86. optimizes the code.  A study of code optimization methods is 
  87. very interesting, but beyond the scope of this tutorial.  Note 
  88. that a constant can also be volatile, which means that you cannot 
  89. change it, but the system can modify it through some hardware 
  90. function.
  91.  
  92. Ignore the output statement given in line 23 for a few minutes.  
  93. We will study it in some detail later in this chapter.  If you 
  94. are experienced in the K&R style of programming, you may find 
  95. line 5 and 21 a little strange.  This illustrates prototyping and 
  96. the modern method of function definition as defined by the ANSI-C 
  97. standard.  Prototyping is optional in C but absolutely required 
  98. in C++.  For that reason, chapter 4 of this tutorial is devoted 
  99. entirely to prototyping.
  100.  
  101. It would be advantageous for you to compile and execute this 
  102. program with your C++ compiler to see if you get the same result 
  103. as given in the comments at the end of the listing.  One of the 
  104. primary purposes of compiling it is to prove that your compiler 
  105. is loaded and executing properly.
  106.  
  107.  
  108. THE SCOPE OPERATOR
  109. -----------------------------------------------------------------
  110. The example program named SCOPEOP.CPP           =================
  111. illustrates another construct that is new to       SCOPEOP.CPP
  112. C++.  There is no corresponding construct in    =================
  113. either K&R or ANSI-C.  This allows access to 
  114.  
  115.                                                          Page 1-2
  116.  
  117.                                         Chapter 1 - Simple Things
  118.  
  119. the global variable named index even though there is a local 
  120. variable of the same name within the main function.  The use of 
  121. the double colon in front of the variable name, in lines 11, 13, 
  122. and 16, instructs the system that we are interested in using the 
  123. global variable named index, defined in line 4, rather than the 
  124. local variable defined in line 8.
  125.  
  126. The use of this technique allows access to the global variable 
  127. for any use.  It could be used in calculations, as a function 
  128. parameter, or for any other purpose.  It is not really good 
  129. programming practice to abuse this construct, because it could 
  130. make the code difficult to read.  It would be best to use a 
  131. different variable name instead of reusing this name, but the 
  132. construct is available to you if you find that you need it 
  133. sometime.
  134.  
  135. Be sure to compile and execute this program before proceeding on 
  136. to the next example program where we will discuss the cout 
  137. operator used in lines 10, 11, 15, and 16.
  138.  
  139.  
  140. THE iostream LIBRARY
  141. -----------------------------------------------------------------
  142. Examine the example program named MESSAGE.CPP   =================
  143. for our first hint of object oriented              MESSAGE.CPP
  144. programming, even though it is a very simple    =================
  145. one.  In this program, we define a few 
  146. variables and assign values to them for use in the output 
  147. statements illustrated in lines 17 through 20, and in lines 23 
  148. through 26.  The operator cout is the output function to the 
  149. standard device, the monitor, but works a little differently from 
  150. our old familiar printf() function, because we do not have to 
  151. tell the system what type we are outputting.
  152.  
  153. C++, like the C language itself, has no input or output 
  154. operations as part of the language itself, but defines the stream 
  155. library to add input and output functions in a very elegant 
  156. manner.  The stream library is included in this program in line 2.
  157.  
  158. The operator <<, sometimes called the "put to" operator but more 
  159. properly called the insertion operator, tells the system to 
  160. output the variable or constant following it, but lets the 
  161. system decide how to output the data.  In line 17, we first tell 
  162. the system to output the string, which it does by copying 
  163. characters to the monitor, then we tell it to output the value 
  164. of index.  Notice however, that we fail to tell it what the type 
  165. is or how to output the value.  Since we don't tell the system 
  166. what the type is, it is up to the system to determine what the 
  167. type is and to output the value accordingly.  After the system 
  168. finds the correct type, we also leave it up to the system to use 
  169. the built in default as to how many characters should be used for 
  170. this output.  In this case, we find that the system uses exactly 
  171. as many characters as needed to output the data, with no leading 
  172.  
  173.                                                          Page 1-3
  174.  
  175.                                         Chapter 1 - Simple Things
  176.  
  177. or trailing blanks, which is fine for this output.  Finally, the 
  178. newline character is output as a single character string, and the 
  179. line of code is terminated with a semicolon.
  180.  
  181. When we called the cout output function in line 17, we actually 
  182. called two different functions because we used it to output two 
  183. strings and a variable of type int.  This is the first hint at 
  184. object oriented programming because we simply broadcast a message 
  185. to the system to print out a value, and let the system find an 
  186. appropriate function to do so.  We are not required to tell the 
  187. system exactly how to output the data, we only tell it to output 
  188. it.  This is a very weak example of object oriented programming, 
  189. and we will study it in much more depth later in this tutorial.
  190.  
  191. In line 18, we tell the system to output a different string, 
  192. followed by a floating point number, and another string of one 
  193. character, the newline character.  In this case, we told it to 
  194. output a floating point number without telling it that it was a 
  195. floating point number, once again letting the system choose the 
  196. appropriate output means based on its type.  We did lose a bit of 
  197. control in the transaction, however, because we had no control 
  198. over how many significant digits to print before or after the 
  199. decimal point.  We chose to let the system decide how to format 
  200. the output data.
  201.  
  202. The variable named letter is of type char, and is assigned the 
  203. value of the uppercase X in line 14, then printed as a letter in 
  204. line 19.
  205.  
  206. Because C++ has several other operators and functions available 
  207. with streams, you have complete flexibility in the use of the 
  208. stream output functions.  You should refer to your compiler 
  209. documentation for details of other available formatting commands.  
  210. Because it is expected to be mandated by the upcoming ANSI-C++ 
  211. standard, the cout and printf() statements can be mixed in any 
  212. way you desire.  However all compilers do not yet conform to this 
  213. standard and some use different forms of buffering for the two 
  214. kinds of output.  This results in scrambled output, but should be 
  215. easy for the student to repair the output in such a way that only 
  216. one form is used, either the cout or the printf().
  217.  
  218.  
  219. MORE ABOUT THE stream LIBRARY
  220. -----------------------------------------------------------------
  221. The stream library was defined for use with C++ in order to add 
  222. to the execution efficiency of the language.  The printf() 
  223. function was developed early in the life of the C language and is 
  224. meant to be all things to all programmers.  As a result, it 
  225. became a huge function with lots of extra baggage, most of which 
  226. is used by only a few programmers.  By defining the small special 
  227. purpose stream library, the designer of C++ allows the programmer 
  228. to use somewhat limited formatting capabilities, which are still 
  229. adequate for most programming jobs.  If more elaborate formatting 
  230.  
  231.                                                          Page 1-4
  232.  
  233.                                         Chapter 1 - Simple Things
  234.  
  235. capabilities are required, the complete printf() library is 
  236. available within any C++ program, and eventually the two types of 
  237. outputs can be freely mixed.  If your compiler does not yet 
  238. support this, it will be up to you to see that only one type is 
  239. used in any given program.  Although it is not all illustrated 
  240. here, there is a full set of formatting functions available in 
  241. the C++ stream library.  Check your compiler documentation for 
  242. the complete list.
  243.  
  244. Lines 23 through 26 illustrate some of the additional features of 
  245. the stream library which can be used to output data in a very 
  246. flexible yet controlled format.  The value of index is printed 
  247. out in decimal, octal, and hexadecimal format in lines 23 through 
  248. 25.  When one of the special stream operators, dec, oct, or hex, 
  249. is output, all successive output will be in that number base.  
  250. Looking ahead to line 30, we find the value of index printed in 
  251. hex format due to the selection of the hexadecimal base in line 
  252. 25.  If none of these special stream operators are output, the 
  253. system defaults to decimal format.
  254.  
  255.  
  256. THE cin OPERATOR
  257. -----------------------------------------------------------------
  258. In addition to the cout operator, there is a cin operator which 
  259. is used to read data from the standard input device, usually the 
  260. keyboard.  The cin operator uses the >> operator, usually called 
  261. the "get from" operator but properly called the extraction 
  262. operator.  It has most of the flexibility of the cout operator.  
  263. A brief example of the use of the cin operator is given in lines 
  264. 28 through 30.  The special stream operators, dec, oct, and hex, 
  265. also select the number base for the cin stream separately from 
  266. the cout stream.  If none is specified, the input stream also 
  267. defaults to decimal.
  268.  
  269. In addition to the cout operator and the cin operator there is 
  270. one more standard operator, the cerr, which is used to output to 
  271. the error handling device.  This device cannot be redirected to a 
  272. file like the output to the cout can be.  The three operators, 
  273. cout, cin, and cerr, correspond to the stdout, the stdin, and the 
  274. stderr stream pointers of the C programming language.  Their use 
  275. will be illustrated throughout the remainder of this tutorial.
  276.  
  277. The stream library also has file I/O capability which will be 
  278. briefly illustrated in the next example program.
  279.  
  280. Be sure to compile and execute this program before going on to 
  281. the next one.  Remember that the system will ask you to enter an 
  282. integer value which will be echoed back to the monitor, but 
  283. changed to the hexadecimal base.
  284.  
  285.  
  286.  
  287.  
  288.  
  289.                                                          Page 1-5
  290.  
  291.                                         Chapter 1 - Simple Things
  292.  
  293. FILE STREAM OPERATIONS
  294. -----------------------------------------------------------------
  295. Examine the example program named FSTREAM.CPP   =================
  296. for examples of the use of streams with            FSTREAM.CPP
  297. files.  In this program a file is opened for    =================
  298. reading, another for writing, and a third 
  299. stream is opened to the printer to illustrate the semantics of 
  300. stream operations on a file.  Both input and output files are of 
  301. type FILE in C programs, but the ifstream type is used for file 
  302. input and the ofstream is used for output files.  This is 
  303. illustrated in lines 8 through 10 of this example program.
  304.  
  305. The only difference between the streams in the last program and 
  306. the streams in this program is the fact that in the last program, 
  307. the streams were already opened for us by the system.  You will 
  308. note that the stream named printer is used in the same way we 
  309. used the cout operator in the last program.  Finally, because we 
  310. wish to exercise good programming practice, we close all of the 
  311. files we have opened prior to ending the program.
  312.  
  313. This is our first example of object oriented programming because 
  314. we are actually using objects in this program.  The object named 
  315. infile is told to open itself in line 17, then it is told to get 
  316. one character at a time in line 41, and finally it is told to 
  317. close itself in line 48.  The "dot" notation is used with objects 
  318. in a similar manner that structures are used in C.  The name of 
  319. the object is mentioned, followed by a "dot", and followed by the 
  320. name of the action that the object is to execute.  This 
  321. terminology will be used in great profusion later in this 
  322. tutorial, so don't worry about it at this time.  The objects 
  323. outfile and printer are manipulated in exactly the same manner.
  324.  
  325. For more information on the stream file I/O library, see Bjarne 
  326. Stroustrup's book which is listed in the introduction to this 
  327. tutorial, or refer to your compiler documentation.  Don't worry 
  328. too much about it yet, after you learn the terminology by 
  329. studying the rest of this tutorial, you will be able to return 
  330. to a personal study of the stream library, and profit greatly 
  331. from the study.
  332.  
  333. Be sure to compile and execute this program.  When you execute 
  334. it, it will request a file to be copied.  You can enter the name 
  335. of any ASCII file that resides in the current directory.
  336.  
  337.  
  338. VARIABLE DEFINITIONS
  339. -----------------------------------------------------------------
  340. Examine the file named VARDEF.CPP for a few    ==================
  341. more additions to the C++ language which aid       VARDEF.CPP
  342. in writing a clear and easy to understand      ==================
  343. program.  In C++, as in ANSI-C, global and 
  344. static variables are automatically initialized to zero when they 
  345. are declared.  The variables named index in line 4, and goofy in 
  346.  
  347.                                                          Page 1-6
  348.  
  349.                                         Chapter 1 - Simple Things
  350.  
  351. line 26 are therefore automatically initialized to zero.  Of 
  352. course, you can still initialize either to some other value if 
  353. you so desire.  Global variables are sometimes called external 
  354. since they are external to any functions.
  355.  
  356. Automatic variables, those declared inside of any function, are 
  357. not automatically initialized but will contain the value that 
  358. happens to be in the location where they are defined, which must 
  359. be considered a garbage value.  The variable named stuff in line 
  360. 8, therefore does not contain a valid value, but some garbage 
  361. value which should not be used for any meaningful purpose.  In 
  362. line 11, it is assigned a value based on the initialized value of 
  363. index and it is then displayed on the monitor for your 
  364. examination.
  365.  
  366.  
  367. THE REFERENCE VARIABLE
  368. -----------------------------------------------------------------
  369. Notice the ampersand in line 9.  This defines another_stuff as a 
  370. reference variable which is a new addition to C++.  The reference 
  371. variable should not be used very often, if ever, in this context, 
  372. but this is a very simple example used to introduce the reference 
  373. variable and discuss its use and operation.  The reference 
  374. variable is not quite the same as any other variable used in C 
  375. because it operates like a self dereferencing pointer.  Following 
  376. its initialization, the reference variable becomes a synonym for 
  377. the variable stuff, and changing the value of stuff will change 
  378. the value of another_stuff because they are both actually 
  379. referring to the same variable.  The synonym can be used to 
  380. access the value of the variable for any legal purpose in the 
  381. language.  It should be pointed out that a reference variable 
  382. must be initialized to reference some other variable when it is 
  383. declared or the compiler will respond with an error.  Following 
  384. initialization, the reference variable cannot be changed to refer 
  385. to a different actual variable.
  386.  
  387. The use of the reference variable in this way can lead to very 
  388. confusing code, but it has another use where it can make the code 
  389. very clear and easy to understand.  We will study the proper use 
  390. of the reference variable in chapter 4 of this tutorial. 
  391.  
  392.  
  393. DEFINITIONS ARE EXECUTABLE STATEMENTS
  394. -----------------------------------------------------------------
  395. Coming from your background of C, you will find the statement in 
  396. line 16 very strange, but this is legal in C++.  Anyplace it is 
  397. legal to put an executable statement, it is also legal to declare 
  398. a new variable because a data declaration is defined as an 
  399. executable statement in C++.  In this case, we define the new 
  400. variable named more_stuff and initialize it to the value of 13.  
  401. It has a scope from the point where it is defined to the end of 
  402. the block in which it is defined, so it is valid throughout the 
  403.  
  404.  
  405.                                                          Page 1-7
  406.  
  407.                                         Chapter 1 - Simple Things
  408.  
  409. remainder of the main program.  The variable named goofy is 
  410. declared even later in line 26.
  411.  
  412. It is significant that the variable is declared near its point of 
  413. usage.  This makes it easier to see just what the variable is 
  414. used for, since it has a much more restricted scope of validity.  
  415. When you are debugging a program, it is convenient if the 
  416. variable declaration is located in close proximity to where you 
  417. are debugging the code.
  418.  
  419.  
  420. WHAT ABOUT definition AND declaration?
  421. -----------------------------------------------------------------
  422. The words definition and declaration refer to two different 
  423. things in C++, and in ANSI-C also for that matter.  They really 
  424. are different and have different meanings, so we should spend a 
  425. little time defining exactly what the words mean in C++.  A 
  426. declaration provides information to the compiler about the 
  427. characteristics of something such as a type or a function but it 
  428. doesn't actually define any code to be used in the executable 
  429. program.  A definition, on the other hand, actually defines 
  430. something that will exist in the executable program, either some 
  431. useful variables, or some executable code, and you are required 
  432. to have one and only one definition of each entity in the 
  433. program.  In short, a declaration introduces a name into the 
  434. program and a definition introduces some code and requires 
  435. memory space to store something.
  436.  
  437. If we declare a struct, we are only declaring a pattern to tell 
  438. the compiler how to store data later when we define one or more 
  439. variables of that type.  But when we define some variables of 
  440. that type, we are actually declaring their names for use by the 
  441. compiler, and defining a storage location to store the values of 
  442. the variables.  Therefore, when we define a variable, we are 
  443. actually declaring it and defining it at the same time.
  444.  
  445. C permits multiple definitions of a variable in any given 
  446. namespace, provided the definitions are the same and it generates 
  447. only a single variable for the multiple definitions.  C++, 
  448. however, does not permit redefinition of a variable or any other 
  449. entity for a very definite reason that we will discuss later.
  450.  
  451. We will refer to these definitions many times throughout the 
  452. course of this tutorial so if this is not clear now, it will 
  453. clear up later.
  454.  
  455.  
  456. A BETTER for LOOP
  457. -----------------------------------------------------------------
  458. Take careful notice of the for loop defined in line 20.  This 
  459. loop is a little clearer than the for loop that is available in 
  460. ANSI-C, because the loop index is defined in the for loop itself.  
  461. The scope of this loop index is from its declaration to the end 
  462.  
  463.                                                          Page 1-8
  464.  
  465.                                         Chapter 1 - Simple Things
  466.  
  467. of the enclosing block.  In this case its scope extends to line 
  468. 29 since the closing brace in line 29 corresponds to the most 
  469. recent opening brace prior to the declaration of the variable.  
  470. Since the variable is still available, it can be used for another 
  471. loop index or for any other purpose which an integer type 
  472. variable can legally be used for.  The variable named count2 is 
  473. declared and initialized during each pass through the loop 
  474. because it is declared within the block controlled by the for 
  475. loop.  Its scope is only the extent of the loop so that it is 
  476. automatically deallocated each time the loop is completed.  It is 
  477. therefore declared, initialized, used and deallocated five times, 
  478. once for each pass through the loop.
  479.  
  480. You will notice that the variable count2 is assigned a numerical 
  481. value in line 22 but when it is printed out, a character value is 
  482. actually output.  This is because C++ (version 2.0 and later) is 
  483. careful to use the correct type for output.
  484.  
  485. Finally, as mentioned earlier, the static variable named goofy is 
  486. declared and automatically initialized to zero in line 26.  Its 
  487. scope is from the point of its declaration to the end of the 
  488. block in which it is declared, line 29.
  489.  
  490. Be sure to compile and execute this program.
  491.  
  492.  
  493. OPERATOR PRECEDENCE
  494. -----------------------------------------------------------------
  495. Operator precedence is identical to that defined for ANSI-C so no 
  496. attempt will be made here to define it.  There is a small 
  497. difference when some operators are overloaded which we will learn 
  498. to do later in this tutorial.  Some of the operators act slightly 
  499. different when overloaded than the way they operate with elements 
  500. of the predefined language.
  501.  
  502. Do not worry about the previous paragraph, it will make sense 
  503. later in this tutorial after we have studied a few more topics.
  504.  
  505.  
  506. PROGRAMMING EXERCISES
  507. -----------------------------------------------------------------
  508. 1.  Write a program that displays your name and date of birth on 
  509.     the monitor three times using the cout function.  Define any 
  510.     variables you use as near as possible to their point of 
  511.     usage.
  512.     
  513. 2.  Write a program with a few const values and volatile 
  514.     variables and attempt to change the value of the constants to 
  515.     see what kind of error message your compiler will give you.
  516.  
  517. 3.  Write a program that uses streams to interactively read in 
  518.     your birthday with three different cin statements.  Print 
  519.     your birthday in octal, decimal, and hexadecimal notation 
  520.     just for the practice.
  521.                                                          Page 1-9
  522.