home *** CD-ROM | disk | FTP | other *** search
/ minnie.tuhs.org / unixen.tar / unixen / PDP-11 / Trees / V6 / usr / doc / ctut / ct3 < prev    next >
Encoding:
Text File  |  1975-06-26  |  10.8 KB  |  561 lines

  1. .NH
  2. Increment and Decrement Operators
  3. .PP
  4. In addition to the usual
  5. `\(mi',
  6. C also has two other interesting
  7. unary
  8. operators, `++' (increment) and `\(mi\(mi' (decrement).
  9. Suppose we want to count the lines
  10. in a file.
  11. .E1
  12. main( ) {
  13.     int c,n;
  14.     n = 0;
  15.     while( (c=getchar( )) != '\\0' )
  16.         if( c \*= '\\n' )
  17.             \*+n;
  18.     printf("%d lines\\n", n);
  19. }
  20. .E2
  21. .UL \*+n 
  22. is equivalent to
  23. .UL n=n+1
  24. but clearer,
  25. particularly when
  26. .UL n
  27. is a complicated expression.
  28. `++' and `\(mi\(mi' can be applied only to
  29. .UL int's
  30. and
  31. .UL char's
  32. (and
  33. .UL pointers
  34. which we haven't got to yet).
  35. .PP
  36. The unusual feature of `++' and `\(mi\(mi' is that they
  37. can be used either before or after a variable.
  38. The value of
  39. .UL \*+k
  40. is the value of
  41. .UL k
  42. .ul
  43. after
  44. it has been incremented.
  45. The value of
  46. .UL k\*+
  47. is
  48. .UL k
  49. .ul
  50. before
  51. it is incremented.
  52. Suppose
  53. .UL k
  54. is 5.
  55. Then
  56. .E1
  57. x = \*+k;
  58. .E2
  59. increments
  60. .UL k
  61. to 6 and then sets
  62. .UL x
  63. to
  64. the resulting value,
  65. i.e., to 6.
  66. But
  67. .E1
  68. x = k\*+;
  69. .E2
  70. first sets
  71. .UL x
  72. to
  73. to 5,
  74. and
  75. .ul
  76. then
  77. increments
  78. .UL k
  79. to 6.
  80. The incrementing effect of
  81. .UL \*+k
  82. and
  83. .UL k\*+
  84. is the same,
  85. but their values are respectively 5 and 6.
  86. We shall soon see examples where both of these uses are important.
  87. .NH
  88. Arrays
  89. .PP
  90. In C, as in Fortran or PL/I, it is possible to make arrays
  91. whose elements are basic types.
  92. Thus we can make an array of 10
  93. integers
  94. with the declaration
  95. .E1
  96. int x[10];
  97. .E2
  98. The square brackets
  99. mean
  100. .ul
  101. subscripting;
  102. parentheses are used only for function references.
  103. Array indexes begin at 
  104. .ul
  105. zero,
  106. so the elements of
  107. .UL x
  108. are
  109. .E1
  110. x[0], x[1], x[2], \*.\*.\*., x[9]
  111. .E2
  112. If an array has
  113. .UL n
  114. elements, the largest subscript is
  115. .UL n\(mi1\*.
  116. .PP
  117. Multiple-dimension arrays are provided,
  118. though not much used above two dimensions.
  119. The declaration and use look like
  120. .E1
  121. int name[10] [20];
  122. n = name[i+j] [1] + name[k] [2];
  123. .E2
  124. Subscripts can be arbitrary integer expressions.
  125. Multi-dimension arrays are stored by row (opposite to Fortran),
  126. so the rightmost subscript varies fastest;
  127. .UL name
  128. has 10 rows and 20 columns.
  129. .PP
  130. Here is a program which reads a line,
  131. stores it in a buffer,
  132. and prints its length (excluding the newline at the end).
  133. .E1
  134. .ne 8
  135. main( ) {
  136.     int n, c;
  137.     char line[100];
  138.     n = 0;
  139.     while( (c=getchar( )) != '\\n' ) {
  140.         if( n < 100 )
  141.             line[n] = c;
  142.         n\*+;
  143.     }
  144.     printf("length = %d\\n", n);
  145. }
  146. .E2
  147. .PP
  148. As a more complicated problem,
  149. suppose we want to print the count for each line in the input,
  150. still storing the first 100 characters of each line.
  151. Try it as an exercise before looking at the solution:
  152. .E1
  153. main( ) {
  154.     int n, c; char line[100];
  155.     n = 0;
  156.     while( (c=getchar( )) != '\\0' ) 
  157.         if( c \*= '\\n' ) {
  158.             printf("%d\n", n);
  159.             n = 0;
  160.         }
  161.         else {
  162.             if( n < 100 ) line[n] = c;
  163.             n\*+;
  164.         }
  165. }
  166. .E2
  167. .NH
  168. Character Arrays; Strings
  169. .PP
  170. Text is usually kept as an array of characters,
  171. as we did with
  172. .UL line[ 
  173. .UL ]
  174. in the example above.
  175. By convention in C,
  176. the last character in a character array should be a `\\0'
  177. because most programs that manipulate character arrays
  178. expect it.
  179. For example,
  180. .UL printf
  181. uses the `\\0' to detect the end of a character array
  182. when printing it out with a `%s'.
  183. .PP
  184. We can copy a character array
  185. .UL s
  186. into another
  187. .UL t
  188. like this:
  189. .E1
  190.     i = 0;
  191.     while( (t[i]=s[i]) != '\\0' )
  192.         i\*+;
  193. .E2
  194. .PP
  195. Most of the time we have to put in our own `\\0' at the end of a string;
  196. if we want to print the line with
  197. .UL printf,
  198. it's necessary.
  199. This code prints the character count before the line:
  200. .E1
  201. main( ) {
  202.     int n;
  203.     char line[100];
  204.     n = 0;
  205.     while( (line[n\*+]=getchar( )) != '\\n' );
  206.     line[n] = '\\0';
  207.     printf("%d:\\t%s", n, line);
  208. }
  209. .E2
  210. Here we increment 
  211. .UL n
  212. in the subscript itself,
  213. but only after the previous value has been used.
  214. The character is read, placed in 
  215. .UL line[n],
  216. and only then
  217. .UL n
  218. is incremented.
  219. .PP
  220. There is one place and one place only
  221. where C puts in the `\\0' at the end of a character array for you,
  222. and that is in the construction
  223. .E1
  224. "stuff between double quotes"
  225. .E2
  226. The compiler puts a `\\0' at the end automatically.
  227. Text enclosed in double quotes is called a
  228. .ul
  229. string;
  230. its properties are precisely those of an (initialized) array of characters.
  231. .NH
  232. For Statement
  233. .PP
  234. The
  235. .UL for
  236. statement is a somewhat generalized
  237. .UL while
  238. that lets us put the initialization and increment parts
  239. of a loop into a single statement along with the test.
  240. The general form of the
  241. .UL for
  242. is
  243. .E1
  244. for( initialization; expression; increment )
  245.     statement
  246. .E2
  247. The meaning is exactly
  248. .E1
  249.     initialization;
  250.     while( expression ) {
  251.         statement
  252.         increment;
  253.     }
  254. .E2
  255. Thus, the following code does the same array copy as the example in the previous section:
  256. .E1
  257.     for( i=0; (t[i]=s[i]) != '\\0'; i\*+ );
  258. .E2
  259. This slightly more
  260. ornate example adds up the elements of an array:
  261. .E1
  262.     sum = 0;
  263.     for( i=0; i<n; i\*+)
  264.         sum = sum + array[i];
  265. .E2
  266. .PP
  267. In the
  268. .UL for
  269. statement,
  270. the initialization
  271. can be left out if you want,
  272. but the semicolon has to be there.
  273. The increment is
  274. also optional.
  275. It is
  276. .ul
  277. not
  278. followed by a semicolon.
  279. The second clause, the test,
  280. works the same way as in the
  281. .UL while:
  282. if the expression is true (not zero)
  283. do another loop,
  284. otherwise get on with the next statement.
  285. As with the
  286. .UL while,
  287. the
  288. .UL for
  289. loop may be done zero times.
  290. If the expression is left out, it is taken to be always true, so
  291. .E1
  292. for( ; ; ) \*.\*.\*.
  293. .E2
  294. and
  295. .E1
  296. while( 1 ) \*.\*.\*.
  297. .E2
  298. are both infinite loops.
  299. .PP
  300. You might ask why we use a
  301. .UL for
  302. since it's so much like a
  303. .UL while\*.
  304. (You might also ask why we use a
  305. .UL while
  306. because...)
  307. The
  308. .UL for 
  309. is usually preferable because it keeps the code where it's used
  310. and sometimes eliminates the need for compound statements,
  311. as in this code that zeros a two-dimensional array:
  312. .E1
  313. for( i=0; i<n; i\*+ )
  314.     for( j=0; j<m; j\*+ )
  315.         array[i][j] = 0;
  316. .E2
  317. .NH
  318. Functions; Comments
  319. .PP
  320. Suppose we want,
  321. as part of a larger program,
  322. to count the occurrences of the ascii
  323. characters in some input text.
  324. Let us also map illegal characters
  325. (those with value>127 or <0) into one pile.
  326. Since this is presumably an isolated part of the program,
  327. good practice dictates making it a separate function.
  328. Here is one way:
  329. .E1
  330. .ne 7
  331. main(~) {
  332.     int hist[129];        /\** 128 legal chars + 1 illegal group \**/
  333.     \*.\*.\*.
  334.     count(hist, 128);    /\** count the letters into hist \**/
  335.     printf( \*.\*.\*. );        /\** comments look like this; use them \**/
  336.     \*.\*.\*.        /\** anywhere blanks, tabs or newlines could appear \**/
  337. }
  338. .SP
  339. count(buf, size)
  340.    int size, buf[ ]; {
  341.     int i, c;
  342.     for( i=0; i<=size; i\*+ )
  343.         buf[i] = 0;            /\** set buf to zero \**/
  344.     while( (c=getchar(~)) != '\\0' ) {    /\** read til eof \**/
  345.         if( c > size \*| c < 0 )
  346.             c = size;        /\** fix illegal input \**/
  347.         buf[c]\*+;
  348.     }
  349.     return;
  350. }
  351. .E2
  352. We have already seen many examples of calling a function,
  353. so let us concentrate on how to 
  354. .ul
  355. define
  356. one.
  357. Since 
  358. .UL count
  359. has two arguments, we need to declare them,
  360. as shown,
  361. giving their types, and in the case of
  362. .UL buf,
  363. the fact
  364. that it is an array.
  365. The declarations of arguments go
  366. .ul
  367. between
  368. the argument list
  369. and the opening `{'.
  370. There is no need to specify the size of the array 
  371. .UL buf,
  372. for it is defined outside of
  373. .UL count\*.
  374. .PP
  375. The
  376. .UL return
  377. statement simply says to go back to the calling routine.
  378. In fact, we could have omitted it,
  379. since a return is implied at the end of a function.
  380. .PP
  381. What if we wanted 
  382. .UL count
  383. to return a value, say the number of characters read?~
  384. The 
  385. .UL return
  386. statement allows for this too:
  387. .E1
  388.     int i, c, nchar;
  389.     nchar = 0;
  390.     \*.\*.\*.
  391.     while( (c=getchar(~)) != '\\0' ) {
  392.         if( c > size \*| c < 0 )
  393.             c = size;
  394.         buf[c]\*+;
  395.         nchar\*+;
  396.     }
  397.     return(nchar);
  398. .E2
  399. Any expression can appear within the parentheses.
  400. Here is a function to compute the minimum of two integers:
  401. .E1
  402. .ne 4
  403. min(a, b)
  404.    int a, b; {
  405.     return( a < b ? a : b );
  406. }
  407. .E2
  408. .PP
  409. .PP
  410. To copy a character array,
  411. we could write the function
  412. .E1
  413. .ne 5
  414. strcopy(s1, s2)        /\** copies s1 to s2 \**/
  415.    char s1[ ], s2[ ]; {
  416.     int i;
  417.     for( i = 0; (s2[i] = s1[i]) != '\\0'; i\*+ );
  418. }
  419. .E2
  420. As is often the case, all the work is done by the assignment statement
  421. embedded in the test part of the
  422. .UL for\*.
  423. Again, the declarations of the arguments 
  424. .UL s1 
  425. and
  426. .UL s2
  427. omit the sizes, because they don't matter to
  428. .UL strcopy\*.
  429. (In the section on pointers, we will see a more efficient
  430. way to do a string copy.)
  431. .PP
  432. There is a subtlety
  433. in function usage which can trap the unsuspecting Fortran programmer.
  434. Simple variables (not arrays) are passed in C by
  435. ``call by value'',
  436. which means that the called function is given
  437. a copy of its arguments,
  438. and doesn't know their addresses.
  439. This makes it impossible to change the value of one of the actual input arguments.
  440. .a
  441. .PP
  442. There are two ways out of this dilemma.
  443. One is to make special arrangements to pass to the function
  444. the address of a variable instead of its value.
  445. The other is to make the variable a global or external variable,
  446. which is known to each function by its name.
  447. We will discuss both possibilities in the next few sections.
  448. .NH
  449. Local and External Variables
  450. .PP
  451. If we say
  452. .E1
  453. f( ) {
  454.     int x;
  455.     \*.\*.\*.
  456. }
  457. g( ) {
  458.     int x;
  459.     \*.\*.\*.
  460. }
  461. .E2
  462. each 
  463. .UL x
  464. is
  465. .ul
  466. local
  467. to its own routine _
  468. the
  469. .UL x
  470. in
  471. .UL f
  472. is unrelated to the
  473. .UL x
  474. in
  475. .UL g\*.
  476. (Local variables are also called ``automatic''.)
  477. Furthermore each local variable in a routine appears only when
  478. the function is called, and
  479. .ul
  480. disappears
  481. when the function is exited.
  482. Local variables have no memory from one call to the next
  483. and must be explicitly initialized upon each entry.
  484. (There is a
  485. .UL static
  486. storage class for making local variables with memory;
  487. we won't discuss it.)
  488. .PP
  489. As opposed to local variables,
  490. .ul
  491. external variables
  492. are defined external to all functions,
  493. and are (potentially) available to all functions.
  494. External storage
  495. .ne 6
  496. always remains in existence.
  497. To make variables external we have to
  498. .ul
  499. define
  500. them external to all functions,
  501. and, wherever we want to use them,
  502. make a
  503. .ul
  504. declaration.
  505. .E1
  506. main(~) {
  507.     extern int nchar, hist[ ];
  508.     \*.\*.\*.
  509.     count(~);
  510.     \*.\*.\*.
  511. }
  512. .SP
  513. .ne 7
  514. count(~) {
  515.     extern int nchar, hist[ ];
  516.     int i, c;
  517.     \*.\*.\*.
  518. }
  519. .SP
  520. int    hist[129];    /\** space for histogram \**/
  521. int    nchar;        /\** character count \**/
  522. .E2
  523. Roughly speaking, any function that wishes to access an external variable
  524. must contain an
  525. .UL extern
  526. declaration
  527. for it.
  528. The declaration is the same as others,
  529. except for the added keyword
  530. .UL extern\*.
  531. Furthermore, there must somewhere be a
  532. .ul
  533. definition
  534. of the external variables external to all functions.
  535. .PP
  536. External variables can be initialized;
  537. they are set to zero if not explicitly
  538. initialized.
  539. In its simplest form,
  540. initialization is done by putting the value (which must be a constant) after the definition:
  541. .E1
  542. int    nchar    0;
  543. char    flag    'f';
  544. .ft R
  545.   etc\*.
  546. .E2
  547. This is discussed further in a later section.
  548. .SP
  549. .PP
  550. This ends our discussion of what might be called
  551. the central core of C.
  552. You now have enough to write quite substantial
  553. C programs,
  554. and it would probably be a good idea if you paused
  555. long enough to do so.
  556. The rest of this tutorial
  557. will describe some more ornate constructions,
  558. useful but not essential.
  559. .SP
  560. .SP
  561.