home *** CD-ROM | disk | FTP | other *** search
/ ftp.cse.unsw.edu.au / 2014.06.ftp.cse.unsw.edu.au.tar / ftp.cse.unsw.edu.au / pub / doc / papers / misc / cs.toronto.edu:programming / ihstyle.tbl.ms < prev    next >
Encoding:
Text File  |  1992-10-18  |  38.2 KB  |  1,214 lines

  1. .RP
  2. .TL
  3. Indian Hill C Style and Coding Standards
  4. .br
  5. as amended for U of T Zoology
  6. .UX
  7. .AU
  8. L.W. Cannon
  9. R.A. Elliott
  10. L.W. Kirchhoff
  11. J.H. Miller
  12. J.M. Milner
  13. R.W. Mitze
  14. E.P. Schan
  15. N.O. Whittington
  16. .AI
  17. Bell Labs
  18. .AU
  19. Henry Spencer
  20. .AI
  21. Zoology Computer Systems
  22. University of Toronto
  23. .AB
  24. This document is an annotated
  25. (by the last author) version of the original paper of the same title.
  26. It describes a set of coding standards and recommendations
  27. which are local standards for officially-supported
  28. .UX
  29. programs.
  30. The scope is coding style, not functional organization.
  31. .AE
  32. .\"--------------------
  33. .\" Footnote numbering
  34. .ds f \\u\\n+f\\d
  35. .nr f 0 1
  36. .ds F \\n+F.
  37. .nr F 0 1
  38. .\"--------------------
  39. .NH
  40. Introduction
  41. .PP
  42. This document is a result of a committee formed at Indian Hill to establish
  43. a common set of coding standards and recommendations for the Indian Hill
  44. community.
  45. The scope of this work is the coding style,
  46. not the functional organization of programs.
  47. The standards in this document are not specific to ESS programming
  48. only\*f.
  49. .FS
  50. .IP \*F
  51. In fact, they're pretty good general standards.
  52. ``To be clear is professional; not to be clear is unprofessional.'' \(em Sir
  53. Ernest Gowers.
  54. This document is presented unadulterated;  U of T variations, comments,
  55. exceptions, etc. are presented in footnotes.
  56. .FE
  57. We have tried to combine previous work [1,6] on C style into a uniform
  58. set of standards that should be appropriate for any project using C\*f.
  59. .FS
  60. .IP \*F
  61. Of necessity, these standards cannot cover all situations.
  62. Experience and informed judgement count for much.
  63. Inexperienced programmers who encounter unusual situations should
  64. consult 1) code written by experienced C programmers following
  65. these rules, or 2) experienced C programmers.
  66. .FE
  67. .NH
  68. File Organization
  69. .PP
  70. A file consists of various sections that should be separated by
  71. several blank lines.
  72. Although there is no maximum length requirement for source files,
  73. files with more than about 1500 lines are cumbersome to deal with.
  74. The editor may not have enough temp space to edit the file,
  75. compilations will go slower,
  76. etc.
  77. Since most of us use 300 baud terminals,
  78. entire rows of asterisks, for example, should be discouraged\*f.
  79. .FS
  80. .IP \*F
  81. This is not a problem at U of T, or most other sensible places,
  82. but rows of asterisks are still annoying.
  83. .FE
  84. Also lines longer than 80 columns are not handled well by all terminals
  85. and should be avoided if possible\*f.
  86. .FS
  87. .IP \*F
  88. Excessively long lines which result from deep indenting are often
  89. a symptom of poorly-organized code.
  90. .FE
  91. .PP
  92. The suggested order of sections for a file is as follows:
  93. .IP 1.
  94. Any header file includes should be the first thing in the file.
  95. .IP 2.
  96. Immediately after the includes\*f should be a prologue that tells what
  97. .FS
  98. .IP \*F
  99. A common variation, in both Bell code and ours, is to reverse the
  100. order of sections 1 and 2.
  101. This is an acceptable practice.
  102. .FE
  103. is in that file.
  104. A description of the purpose of the objects in the files (whether
  105. they be functions, external data declarations or definitions, or
  106. something else) is more useful than a list of the object names.
  107. .IP 3.
  108. Any typedefs and defines that apply to the file as a whole are next.
  109. .IP 4.
  110. Next come the global (external) data declarations.
  111. If a set of defines applies to a particular piece of global data
  112. (such as a flags word), the defines should be immediately after
  113. the data declaration\*f.
  114. .FS
  115. .IP \*F
  116. Such defines should be indented to put the \fIdefine\fRs one level
  117. deeper than the first keyword of the declaration to which they apply.
  118. .FE
  119. .IP 5.
  120. The functions come last\*f.
  121. .FS
  122. .IP \*F
  123. They should be in some sort of meaningful order.
  124. Top-down is generally better than bottom-up, and a ``breadth-first''
  125. approach (functions on a similar level of abstraction together) is
  126. preferred over depth-first (functions defined as soon as possible
  127. after their calls).
  128. Considerable judgement is called for here.
  129. If defining large numbers of essentially-independent utility
  130. functions, consider alphabetical order.
  131. .FE
  132. .NH 2
  133. File Naming Conventions
  134. .PP
  135. .UX
  136. requires certain suffix conventions for names of files to be processed
  137. by the \fIcc\fR command [5]\*f.
  138. The following suffixes are required:
  139. .IP \(bu
  140. C source file names must end in \fI.c\fR
  141. .IP \(bu
  142. Assembler source file names must end in \fI.s\fR
  143. .PP
  144. In addition the following conventions are universally followed:
  145. .FS
  146. .IP \*F
  147. In addition to the suffix conventions given here,
  148. it is conventional to use `Makefile' (not `makefile') for the
  149. control file for \fImake\fR
  150. and
  151. `README' for a summary of the contents of a directory or directory
  152. tree.
  153. .FE
  154. .IP \(bu
  155. Relocatable object file names end in \fI.o\fR
  156. .IP \(bu
  157. Include header file names end in \fI.h\fR\ \*f or \fI.d\fR
  158. .FS
  159. .IP \*F
  160. Preferred.
  161. An alternate convention that may
  162. be preferable in multi-language environments
  163. is to use the same suffix as an ordinary source file
  164. but with two periods instead of one (e.g. ``foo..c'').
  165. .FE
  166. .IP \(bu
  167. Ldp\*f specification file names end in \fI.b\fR
  168. .FS
  169. .IP \*F
  170. No idea what this is.
  171. .FE
  172. .IP \(bu
  173. Yacc source file names end in \fI.y\fR
  174. .IP \(bu
  175. Lex source file names end in \fI.l\fR
  176. .NH
  177. Header Files
  178. .PP
  179. Header files are files that are included in other files prior to compilation
  180. by the C preprocessor.
  181. Some are defined at the system level like \fIstdio.h\fR which must be included
  182. by any program using the standard I/O library.
  183. Header files are also used to contain data declarations and defines
  184. that are needed by more than one program\*f.
  185. .FS
  186. .IP \*F
  187. Don't use absolute pathnames for header files.
  188. Use the \fI<name>\fR construction for getting them from a standard
  189. place, or define them relative to the current directory.
  190. The \fB\-I\fR option of the C compiler is the best way to handle
  191. extensive private libraries of header files;  it permits reorganizing
  192. the directory structure without having to alter source files.
  193. .FE
  194. Header files should be functionally organized,
  195. i.e., declarations for separate subsystems should be in separate header files.
  196. Also, if a set of declarations is likely to change when code is
  197. ported from one machine to another, those declarations should be
  198. in a separate header file.
  199. .PP
  200. Header files should not be nested.
  201. Some objects like typedefs and initialized data definitions cannot be
  202. seen twice by the compiler in one compilation.
  203. On non-\c
  204. .UX
  205. systems this is also true of uninitialized declarations without the
  206. \fIextern\fR keyword\*f.
  207. .FS
  208. .IP \*F
  209. It should be noted that declaring variables in a header file
  210. is often a poor idea.
  211. Frequently it is a symptom of poor partitioning of code between files.
  212. .FE
  213. This can happen if include files are nested and will cause the
  214. compilation to fail.
  215. .NH
  216. External Declarations
  217. .PP
  218. External declarations should begin in column 1.
  219. Each declaration should be on a separate line.
  220. A comment describing the role of the object being declared should be
  221. included, with the exception that a list of defined constants do not
  222. need comments if the constant names are sufficient documentation.
  223. The comments should be tabbed so that they line up underneath each
  224. other\*f.
  225. .FS
  226. .IP \*F
  227. So should the constant names and their defined values.
  228. .FE
  229. Use the tab character (CTRL I if your terminal doesn't have a separate key)
  230. rather than blanks.
  231. For structure and union template declarations, each element should be alone
  232. on a line with a comment describing it.
  233. The opening brace (\ {\ ) should be on the same line as the structure
  234. tag, and the closing brace should be alone on a line in column 1, i.e.
  235. .DS L
  236. struct boat {
  237.     int wllength;    /* water line length in feet */
  238.     int type;    /* see below */
  239.     long sarea;    /* sail area in square feet */
  240. };
  241. /*
  242.  * defines for boat.type\*f
  243.  */
  244. #define    KETCH    1
  245. #define    YAWL    2
  246. #define    SLOOP    3
  247. #define    SQRIG    4
  248. #define    MOTOR    5
  249. .DE
  250. .FS
  251. .IP \*F
  252. These defines are better put right after the declaration of \fItype\fR,
  253. within the \fIstruct\fR declaration, with enough tabs
  254. after # to indent \fIdefine\fR one level more than
  255. the structure member declarations.
  256. .FE
  257. If an external variable is initialized\*f the equal sign should not be omitted\*f.
  258. .FS
  259. .IP \*F
  260. Any variable whose initial value is important should be
  261. \fIexplicitly\fR initialized, or at the very least should be commented
  262. to indicate that C's default initialization to 0 is being relied on.
  263. .FE
  264. .FS
  265. .IP \*F
  266. The empty initializer, ``{}'', should never be used.
  267. Structure
  268. initializations should be fully parenthesized with braces.
  269. Constants used to initialize longs should be explicitly long.
  270. .FE
  271. .DS
  272. int x = 1;
  273. char *msg = "message";
  274. struct boat winner = {
  275.     40,    /* water line length */
  276.     YAWL,
  277.     600    /* sail area */
  278. };
  279. .DE
  280. \*f
  281. .FS
  282. .IP \*F
  283. In any file which is part of a larger whole rather than a self-contained
  284. program, maximum use should be made of the \fIstatic\fR keyword to make
  285. functions and variables local to single files.
  286. Variables in particular should be accessible from other files
  287. only when there is a clear
  288. need that cannot be filled in another way.
  289. Such usages should be commented to make it clear that another file's
  290. variables are being used; the comment should name the other file.
  291. .FE
  292. .NH
  293. Comments
  294. .PP
  295. Comments that describe data structures, algorithms, etc., should be
  296. in block comment form with the opening /* in column one, a * in column
  297. 2 before each line of comment text\*f, and the closing */ in columns 2-3.
  298. .FS
  299. .IP \*F
  300. Some automated
  301. program-analysis
  302. packages use a different character in this position as
  303. a marker for lines with specific items of information.
  304. In particular, a line with a `-' here in a comment preceding a function
  305. is sometimes assumed to be a one-line summary of the function's purpose.
  306. .FE
  307. .DS L
  308. /*
  309.  *    Here is a block comment.
  310.  *    The comment text should be tabbed over\*f
  311.  *    and the opening /* and closing star-slash
  312.  *    should be alone on a line.
  313.  */
  314. .DE
  315. .FS
  316. .IP \*F
  317. A common practice in both Bell and local code is to
  318. use a space rather than a tab after the *.
  319. This is acceptable.
  320. .FE
  321. .PP
  322. Note that \fIgrep ^.\e*\fR will catch all block comments in the file.
  323. In some cases, block comments inside a function are appropriate, and
  324. they should be tabbed over to the same tab setting as the code that
  325. they describe.
  326. Short comments may appear on a single line indented over to the tab
  327. setting of the code that follows.
  328. .DS
  329. if (argc > 1) {
  330.     /* Get input file from command line. */
  331.     if (freopen(argv[1], "r", stdin) == NULL)
  332.         error("can't open %s\en", argv[1]);
  333. }
  334. .DE
  335. .PP
  336. Very short comments may appear on the same line as the code they describe,
  337. but should be tabbed over far enough to separate them from the statements.
  338. If more than one short comment appears in a block of code they should all
  339. be tabbed to the same tab setting.
  340. .DS
  341. if (a == 2)
  342.     return(TRUE);        /* special case */
  343. else
  344.     return(isprime(a));    /* works only for odd a */
  345. .DE
  346. .NH
  347. Function Declarations
  348. .PP
  349. Each function should be preceded by a block comment prologue that gives
  350. the name and a short description of what the function does\*f.
  351. .FS
  352. .IP \*F
  353. Discussion of non-trivial design decisions is also appropriate,
  354. but avoid duplicating information that is present in (and clear from)
  355. the code.
  356. It's too easy for such redundant information to get out of date.
  357. .FE
  358. If the function returns a value, the type of the value returned should
  359. be alone on a line in column 1 (do not default to \fIint\fR).
  360. If the function does not return a value then it should not be given
  361. a return type.
  362. If the value returned requires a long explanation, it should be given
  363. in the prologue;  otherwise it can be on the same line as the return
  364. type, tabbed over.
  365. The function name and formal parameters should be alone on a line
  366. beginning in column 1.
  367. Each parameter should be declared (do not default to \fIint\fR),
  368. with a comment on a single line.
  369. The opening brace of the function body should also be alone on a line
  370. beginning in column 1.
  371. The function name, argument declaration list, and opening brace
  372. should be separated by a blank line\*f.
  373. .FS
  374. .IP \*F
  375. Neither Bell nor local code has ever included these separating blank
  376. lines, and it is not clear that they add anything useful.
  377. Leave them out.
  378. .FE
  379. All local declarations and code within the function body should be
  380. tabbed over at least one tab.
  381. .PP
  382. If the function uses any external variables, these should have their
  383. own declarations in the function body using the \fIextern\fR keyword.
  384. If the external variable is an array the array bounds must be repeated
  385. in the \fIextern\fR declaration.
  386. There should also be \fIextern\fR declarations for all functions called
  387. by a given function.
  388. This is particularly beneficial to someone picking up code written
  389. by another.
  390. If a function returns a value of type other than \fIint\fR,
  391. it is required by the compiler that such functions be declared before
  392. they are used.
  393. Having the \fIextern\fR delcaration in the calling function's
  394. declarations section avoids all such problems\*f.
  395. .FS
  396. .IP \*F
  397. These rules tend to produce a lot of clutter.
  398. Both Bell and local practice frequently omits \fIextern\fR declarations
  399. for \fIstatic\fR variables and functions.
  400. This is permitted.
  401. Omission of declarations for standard library routines
  402. is also permissible,
  403. although if they \fIare\fR declared it is better to declare them within
  404. the functions that use them rather than globally.
  405. .FE
  406. .PP
  407. In general each variable declaration should be on a separate line with
  408. a comment describing the role played by the variable in the function.
  409. If the variable is external or a parameter of type pointer which is
  410. changed by the function, that should be noted in the comment.
  411. All such comments for parameters and local variables should be
  412. tabbed so that they line up underneath each other.
  413. The declarations should be separated from the function's statements
  414. by a blank line.
  415. .PP
  416. A local variable should not be redeclared in nested blocks\*f.
  417. .FS
  418. .IP \*F
  419. In fact, avoid any local declarations that override declarations
  420. at higher levels.
  421. .FE
  422. Even though this is valid C, the potential confusion is enough
  423. that
  424. \fIlint\fR will complain about it when given the \fB\-h\fR option.
  425. .NH 2
  426. Examples
  427. .PP
  428. .DS L
  429. /*
  430.  *    skyblue()
  431.  *
  432.  *    Determine if the sky is blue.
  433.  */
  434.  
  435. int            /* TRUE or FALSE */
  436. skyblue()
  437.  
  438. {
  439.     extern int hour;
  440.  
  441.     if (hour < MORNING || hour > EVENING)
  442.         return(FALSE);    /* black */
  443.     else
  444.         return(TRUE);    /* blue */
  445. }
  446. .DE
  447. .DS L
  448. /*
  449.  *    tail(nodep)
  450.  *
  451.  *    Find the last element in the linked list
  452.  *    pointed to by nodep and return a pointer to it.
  453.  */
  454.  
  455. NODE *            /* pointer to tail of list */
  456. tail(nodep)
  457.  
  458. NODE *nodep;        /* pointer to head of list */
  459.  
  460. {
  461.     register NODE *np;    /* current pointer advances to NULL */
  462.     register NODE *lp;    /* last pointer follows np */
  463.  
  464.     np = lp = nodep;
  465.     while ((np = np->next) != NULL)
  466.         lp = np;
  467.     return(lp);
  468. }
  469. .DE
  470. .NH
  471. Compound Statements
  472. .PP
  473. Compound statements are statements that contain lists of statements
  474. enclosed in braces.
  475. The enclosed list should be tabbed over one more than the tab position
  476. of the compound statement itself.
  477. The opening left brace should be at the end of the line beginning the
  478. compound statement and the closing right brace should be alone on a
  479. line, tabbed under the beginning of the compound statement.
  480. Note that the left brace beginning a function body is the only occurrence
  481. of a left brace which is alone on a line.
  482. .NH 2
  483. Examples
  484. .PP
  485. .DS
  486. if (expr) {
  487.     statement;
  488.     statement;
  489. }
  490.  
  491. if (expr) {
  492.     statement;
  493.     statement;
  494. } else {
  495.     statement;
  496.     statement;
  497. }
  498. .DE
  499. Note that the right brace before the \fIelse\fR and the right brace
  500. before the \fIwhile\fR of a \fIdo-while\fR statement (below) are the
  501. only places where a right braces appears that is not alone on a line.
  502. .DS
  503. for (i = 0; i < MAX; i++) {
  504.     statement;
  505.     statement;
  506. }
  507.  
  508. while (expr) {
  509.     statement;
  510.     statement;
  511. }
  512.  
  513. do {
  514.     statement;
  515.     statement;
  516. } while (expr);
  517.  
  518. switch (expr) {
  519. case ABC:
  520. case DEF:
  521.     statement;
  522.     break;
  523. case XYZ:
  524.     statement;
  525.     break;
  526. default:
  527.     statement;
  528.     break\*f;
  529. }
  530. .DE
  531. .FS
  532. .IP \*F
  533. This \fIbreak\fR is, strictly speaking, unnecessary, but it is required
  534. nonetheless because it prevents a fall-through error if another \fIcase\fR
  535. is added later after the last one.
  536. .FE
  537. Note that when multiple \fIcase\fR labels are used, they are placed
  538. on separate lines.
  539. The fall through feature of the C \fIswitch\fR statement should
  540. rarely if ever be used when code is executed before falling through
  541. to the next one.
  542. If this is done it must be commented for future maintenance.
  543. .DS
  544. if (strcmp(reply, "yes") == EQUAL) {
  545.     statements for yes
  546.     ...
  547. } else if (strcmp(reply, "no") == EQUAL) {
  548.     statements for no
  549.     ...
  550. } else if (strcmp(reply, "maybe") == EQUAL) {
  551.     statements for maybe
  552.     ...
  553. } else {
  554.     statements for none of the above
  555.     ...
  556. }
  557. .DE
  558. The last example is a generalized \fIswitch\fR statement and the
  559. tabbing reflects the switch between exactly one of several
  560. alternatives rather than a nesting of statements.
  561. .NH
  562. Expressions
  563. .NH 2
  564. Operators
  565. .PP
  566. The old versions of equal-ops =+, =\-, =*, etc. should not be used.
  567. The preferred use is +=, \-=, *=, etc.
  568. All binary operators except . and \-> should be separated from their
  569. operands by blanks\*f.
  570. .FS
  571. .IP \*F
  572. Some judgement is called for in the case of complex expressions,
  573. which may be clearer if the ``inner'' operators are not surrounded
  574. by spaces and the ``outer'' ones are.
  575. .FE
  576. In addition, keywords that are followed by expressions in parentheses
  577. should be separated from the left parenthesis by a blank\*f.
  578. .FS
  579. .IP \*F
  580. \fISizeof\fR is an exception, see the discussion of function calls.
  581. Less logically, so is \fIreturn\fR.
  582. .FE
  583. Blanks should also appear after commas in argument lists to help
  584. separate the arguments visually.
  585. On the other hand, macros with arguments and function calls should
  586. not have a blank between the name and the left parenthesis.
  587. In particular, the C preprocessor requires the left parenthesis
  588. to be immediately after the macro name or else the argument list
  589. will not be recognized.
  590. Unary operators should not be separated from their single operand.
  591. Since C has some unexpected precedence rules,
  592. all expressions involving mixed operators should be fully parenthesized.
  593. .PP
  594. \fIExamples\fR
  595. .DS
  596. a += c + d;
  597. a = (a + b) / (c * d);
  598. strp\->field = str.fl - ((x & MASK) >> DISP);
  599. while (*d++ = *s++)
  600.     ;    /* EMPTY BODY */
  601. .DE
  602. .NH 2
  603. Naming Conventions
  604. .PP
  605. Individual projects will no doubt have their own naming conventions.
  606. There are some general rules however.
  607. .IP \(bu
  608. An initial underscore should not be used for any user-created names\*f.
  609. .FS
  610. .IP \*F
  611. Trailing underscores should be avoided too.
  612. .FE
  613. .UX
  614. uses it for names that the user should not have to know (like
  615. the standard I/O library)\*f.
  616. .FS
  617. .IP \*F
  618. This convention is reserved for system purposes.
  619. If you must have your own private identifiers,
  620. begin them with a capital letter identifying the
  621. package to which they belong.
  622. .FE
  623. .IP \(bu
  624. Macro names, \fItypedef\fR names, and \fIdefine\fR names should be
  625. all in CAPS.
  626. .IP \(bu
  627. Variable names, structure tag names, and function names should be in
  628. lower case\*f.
  629. .FS
  630. .IP \*F
  631. It is best to avoid names that differ only in case, like \fIfoo\fR
  632. and \fIFOO\fR.
  633. The potential for confusion is considerable.
  634. .FE
  635. Some macros (such as \fIgetchar\fR and \fIputchar\fR) are in lower case
  636. since they may also exist as functions.
  637. Care is needed when interchanging macros and functions since functions
  638. pass their parameters by value whereas macros pass their arguments by
  639. name substitution\*f.
  640. .FS
  641. .IP \*F
  642. This difference also means that carefree use of macros requires care
  643. when they are defined.
  644. Remember that complex expressions can be used as parameters,
  645. and operator-precedence problems can arise unless all occurrences of
  646. parameters in the definition have parentheses around them.
  647. There is little that can be done about the problems caused by side
  648. effects in parameters
  649. except to avoid side effects in expressions (a good idea anyway).
  650. .FE
  651. .NH 2
  652. Constants
  653. .PP
  654. Numerical constants should not be coded directly\*f.
  655. .FS
  656. .IP \*F
  657. At the very least, any directly-coded numerical constant must have a
  658. comment explaining the derivation of the value.
  659. .FE
  660. The \fIdefine\fR feature of the C preprocessor should be used to
  661. assign a meaningful name.
  662. This will also make it easier to administer large programs since the
  663. constant value can be changed uniformly by changing only the \fIdefine\fR.
  664. The enumeration data type is the preferred way to handle situations where
  665. a variable takes on only a discrete set of values, since additional type
  666. checking is available through \fIlint\fR.
  667. .PP
  668. There are some cases where the constants 0 and 1 may appear as themselves
  669. instead of as defines.
  670. For example if a \fIfor\fR loop indexes through an array, then
  671. .DS
  672. for (i = 0; i < ARYBOUND; i++)
  673. .DE
  674. is reasonable while the code
  675. .DS
  676. fptr = fopen(filename, "r");
  677. if (fptr == 0)
  678.     error("can't open %s\en", filename);
  679. .DE
  680. is not.
  681. In the last example the defined constant \fINULL\fR is available as
  682. part of the standard I/O library's header file \fIstdio.h\fR and
  683. must be used in place of the 0.
  684. .NH
  685. Portability
  686. .PP
  687. The advantages of portable code are well known.
  688. This section gives some guidelines for writing portable code,
  689. where the definition of portable is taken to mean that a source file
  690. contains portable code if it can be compiled and executed on different
  691. machines with the only source change being the inclusion of possibly
  692. different header files.
  693. The header files will contain defines and typedefs that may vary from
  694. machine to machine.
  695. Reference [1] contains useful information on both style and portability.
  696. Many of the recommendations in this document originated in [1].
  697. The following is a list of pitfalls to be avoided and recommendations
  698. to be considered when designing portable code:
  699. .IP \(bu
  700. First, one must recognize that some things are inherently non-portable.
  701. Examples are code to deal with particular hardware registers such as
  702. the program status word,
  703. and code that is designed to support a particular piece of hardware
  704. such as an assembler or I/O driver.
  705. Even in these cases there are many routines and data organizations
  706. that can be made machine independent.
  707. It is suggested that source file be organized so that the machine-independent
  708. code and the machine-dependent code are in separate files.
  709. Then if the program is to be moved to a new machine,
  710. it is a much easier task to determine what needs to be changed\*f.
  711. .FS
  712. .IP \*F
  713. If you \fI#ifdef\fR dependencies,
  714. make sure that if no machine is specified,
  715. the result is a syntax error, \fInot\fR a default machine!
  716. .FE
  717. It is also possible that code in the machine-independent files
  718. may have uses in other programs as well.
  719. .IP \(bu
  720. Pay attention to word sizes.
  721. The following sizes apply to basic types in C for the machines
  722. that will be used most at IH\*f:
  723. .FS
  724. .IP \*F
  725. The 3B is a Bell Labs machine.
  726. The VAX, not shown in the table, is similar to the 3B in these respects.
  727. The 68000 resembles either the pdp11 or the 3B, depending on the
  728. particular compiler.
  729. .FE
  730. .br
  731. .ne 2i
  732. .TS
  733. center;
  734. l c c c
  735. l r r r.
  736. type    pdp11    3B    IBM
  737. _
  738. char    8    8    8
  739. short    16    16    16
  740. int    16    32    32
  741. long    32    32    32
  742. .TE
  743. In general if the word size is important, \fIshort\fR or \fIlong\fR
  744. should be used to get 16 or 32 bit items on any of the above machines\*f.
  745. .FS
  746. .IP \*F
  747. Any unsigned type other than plain \fIunsigned int\fR should be
  748. \fItypedef\fRed, as such types are highly compiler-dependent.
  749. This is also true of long and short types other than \fIlong int\fR
  750. and \fIshort int\fR.
  751. Large programs should have a central header file which supplies
  752. \fItypedef\fRs for commonly-used width-sensitive types, to make
  753. it easier to change them and to aid in finding width-sensitive code.
  754. .FE
  755. If a simple loop counter is being used where either 16 or 32 bits will
  756. do, then use \fIint\fR, since it will get the most efficient (natural)
  757. unit for the current machine\*f.
  758. .FS
  759. .IP \*F
  760. Beware of making assumptions about the size of pointers.
  761. They are not always the same size as \fIint\fR.
  762. Nor are all pointers always the same size, or freely interconvertible.
  763. Pointer-to-character is a particular trouble spot on machines which
  764. do not address to the byte.
  765. .FE
  766. .IP \(bu
  767. Word size also affects shifts and masks.
  768. The code
  769. .DS
  770. x &= 0177770
  771. .DE
  772. will clear only the three rightmost bits of an \fIint\fR on a PDP11.
  773. On a 3B it will also clear the entire upper halfword.
  774. Use
  775. .DS
  776. x &= ~07
  777. .DE
  778. instead which works properly on all machines\*f.
  779. .FS
  780. .IP \*F
  781. The or operator (\ |\ ) does not have these problems,
  782. nor do bitfields (which, unfortunately, are not very portable due to
  783. defective compilers).
  784. .FE
  785. .IP \(bu
  786. Code that takes advantage of the two's complement representation of
  787. numbers on most machines should not be used.
  788. Optimizations that replace arithmetic operations with equivalent
  789. shifting operations are particularly suspect.
  790. You should weigh the time savings with the potential for obscure
  791. and difficult bugs when your code is moved, say, from a 3B to a 1A.
  792. .IP \(bu
  793. Watch out for signed characters.
  794. On the PDP-11, characters are sign extended when used in expressions,
  795. which is not the case on any other machine.
  796. In particular, \fIgetchar\fR is an integer-valued function (or macro)
  797. since the value of \fIEOF\fR for the standard I/O library is \-1,
  798. which is not possible for a character on the 3B or IBM\*f.
  799. .FS
  800. .IP \*F
  801. Actually, this is not quite the real reason why \fIgetchar\fR returns
  802. \fIint\fR, but the comment is valid:  code which assumes either
  803. that characters are signed or that they are unsigned is unportable.
  804. It is best to completely avoid using \fIchar\fR to hold numbers.
  805. Manipulation of characters as if they were numbers is also
  806. often unportable.
  807. .FE
  808. .IP \(bu
  809. The PDP-11 is unique among processors on which C exists in that the
  810. bytes are numbered from right to left within a word.
  811. All other machines (3B, IBM, Interdata 8/32, Honeywell) number the
  812. bytes from left to right\*f.
  813. .FS
  814. .IP \*F
  815. Actually, there are some more right-to-left machines now, but
  816. the comments still apply.
  817. .FE
  818. Hence any code that depends on the left-right orientation of bits
  819. in a word deserves special scrutiny.
  820. Bit fields within structure members will only be portable so long as
  821. two separate fields are never concatenated and treated as a unit\*f.
  822. .FS
  823. .IP \*F
  824. The same applies to variables in general.
  825. Alignment considerations and loader peculiarities make it very rash
  826. to assume that two consecutively-declared variables are together
  827. in memory, or that a variable of one type is aligned appropriately
  828. to be used as another type.
  829. .FE
  830. [1,3]
  831. .IP \(bu
  832. Do not default the boolean test for non-zero, i.e.
  833. .DS
  834. if (f() != FAIL)
  835. .DE
  836. is better than
  837. .DS
  838. if (f())
  839. .DE
  840. even though \fIFAIL\fR may have the value 0 which is considered to mean
  841. false by C\*f.
  842. This will help you out later when somebody decides that a failure return
  843. should be \-1 instead of 0\ \*f.
  844. .FS
  845. .IP \*F
  846. A particularly notorious case is using \fIstrcmp\fR
  847. to test for string equality, where the result should \fInever\fR
  848. \fIever\fR be defaulted.
  849. The preferred approach is to define a macro \fISTREQ\fR:
  850. .DS
  851. #define STREQ(a, b) (strcmp((a), (b)) == 0)
  852. .DE
  853. .FE
  854. .FS
  855. .IP \*F
  856. An exception is commonly made for predicates, which are functions
  857. which meet the following restrictions:
  858. .IP \(bu
  859. Has no other purpose than to return true or false.
  860. .IP \(bu
  861. Returns 0 for false, 1 for true, nothing else.
  862. .IP \(bu
  863. Is named so that the meaning of (say) a `true' return
  864. is absolutely obvious.
  865. Call a predicate \fIisvalid\fR or \fIvalid\fR, not \fIcheckvalid\fR.
  866. .FE
  867. .IP \(bu
  868. Be suspicious of numeric values appearing in the code.
  869. Even simple values like 0 or 1 could be better expressed using
  870. defines like \fIFALSE\fR and \fITRUE\fR (see previous item)\*f.
  871. .FS
  872. .IP \*F
  873. Actually, \fIYES\fR and \fINO\fR often read better.
  874. .FE
  875. Any other constants appearing in a program would be better expressed
  876. as a defined constant.
  877. This makes it easier to change and also easier to read.
  878. .IP \(bu
  879. Become familiar with existing library functions and defines\*f.
  880. .FS
  881. .IP \*F
  882. But not \fItoo\fR familiar.
  883. The internal details of library facilities, as opposed to their
  884. external interfaces, are subject to change without warning.
  885. They are also often quite unportable.
  886. .FE
  887. You should not be writing your own string compare routine, or making
  888. your own defines for system structures\*f.
  889. .FS
  890. .IP \*F
  891. Or, especially, writing your own code to control terminals.
  892. Use the \fItermcap\fR package.
  893. .FE
  894. Not only does this waste your time, but it prevents your program
  895. from taking advantage of any microcode assists or other
  896. means of improving performance of system routines\*f.
  897. .FS
  898. .IP \*F
  899. It also makes your code less readable, because the reader has to
  900. figure out whether you're doing something special in that reimplemented
  901. stuff to justify its existence.
  902. Furthermore, it's a fruitful source of bugs.
  903. .FE
  904. .IP \(bu
  905. Use \fIlint\fR.
  906. It is a valuable tool for finding machine-dependent constructs as well
  907. as other inconsistencies or program bugs that pass the compiler\*f.
  908. .FS
  909. .IP \*F
  910. The use of \fIlint\fR on all programs is strongly recommended.
  911. It is difficult to eliminate complaints about functions whose return
  912. value is not used (in the current version of C, at least), but most
  913. other messages from \fIlint\fR really do indicate something wrong.
  914. The \-h, \-p, \-a, \-x, and \-c options are worth learning.
  915. All of them will complain about some legitimate things, but they will
  916. also pick up many botches.
  917. Note that \-p checks function-call type-consistency for only a subset of
  918. Unix library routines, so programs should be linted both with and without
  919. this option for best ``coverage''.
  920. .FE
  921. .NH
  922. Lint
  923. .PP
  924. \fILint\fR is a C program checker [2] that examines C source files to
  925. detect and report type incompatibilities, inconsistencies between
  926. function definitions and calls,
  927. potential program bugs, etc.
  928. It is expected that projects will require programs to use \fIlint\fR
  929. as part of the official acceptance procedure\*f.
  930. .FS
  931. .IP \*F
  932. Yes.
  933. .FE
  934. In addition, work is going on in department 5521 to modify \fIlint\fR
  935. so that it will check for adherence to the standards in this document.
  936. .PP
  937. It is still too early to say exactly which of the standards given here
  938. will be checked by \fIlint\fR.
  939. In some cases such as whether a comment is misleading or incorrect there
  940. is little hope of mechanical checking.
  941. In other cases such as checking that the opening brace of a function
  942. body is alone on a line in column 1, the test has already been added\*f.
  943. .FS
  944. .IP \*F
  945. Little of this is relevant at U of T.
  946. The version of \fIlint\fR that we have lacks these mods.
  947. .FE
  948. Future bulletins will be used to announce new additions to \fIlint\fR
  949. as they occur.
  950. .PP
  951. It should be noted that the best way to use \fIlint\fR is not as a barrier
  952. that must be overcome before official acceptance of a program, but
  953. rather as a tool to use whenever major changes or additions to the
  954. code have been made.
  955. \fILint\fR
  956. can find obscure bugs and insure portability before problems occur.
  957. .NH
  958. Special Considerations
  959. .PP
  960. This section contains some miscellaneous do's and don'ts.
  961. .IP \(bu
  962. Don't change syntax via macro substitution.
  963. It makes the program unintelligible to all but the perpetrator.
  964. .IP \(bu
  965. There is a time and a place for embedded assignment statements\*f.
  966. .FS
  967. .IP \*F
  968. The \fB++\fR and \fB\-\-\fR operators count as assignment statements.
  969. So, for many purposes, do functions with side effects.
  970. .FE
  971. In some constructs there is no better way to accomplish the results
  972. without making the code bulkier and less readable.
  973. The \fIwhile\fR loop in section 8.1 is one example of an appropriate
  974. place.
  975. Another is the common code segment:
  976. .DS
  977. while ((c = getchar()) != EOF) {
  978.     process the character
  979. }
  980. .DE
  981. Using embedded assignment statements to improve run-time performance
  982. is also possible.
  983. However, one should consider the tradeoff between increased speed and
  984. decreased maintainability that results when embedded assignments are
  985. used in artificial places.
  986. For example, the code:
  987. .DS
  988. a = b + c;
  989. d = a + r;
  990. .DE
  991. should not be replaced by
  992. .DS
  993. d = (a = b + c) + r;
  994. .DE
  995. even though the latter may save one cycle.
  996. Note that in the long run the time difference between the two will
  997. decrease as the optimizer gains maturity, while the difference in
  998. ease of maintenance will increase as the human memory of what's
  999. going on in the latter piece of code begins to fade\*f.
  1000. .FS
  1001. .IP \*F
  1002. Note also that side effects within expressions can result in code
  1003. whose semantics are compiler-dependent, since C's order of evaluation
  1004. is explicitly undefined in most places.
  1005. Compilers do differ.
  1006. .FE
  1007. .IP \(bu
  1008. There is also a time and place for the ternary \fI?\ :\fR operator
  1009. and the binary comma operator.
  1010. The logical expression operand before the \fI?\ :\fR should be
  1011. parenthesized:
  1012. .DS
  1013. (x >= 0) ? x : \-x
  1014. .DE
  1015. Nested \fI?\ :\fR operators can be confusing and should be avoided
  1016. if possible.
  1017. There are some macros like \fIgetchar\fR where they can be useful.
  1018. The comma operator can also be useful in \fIfor\fR statements to
  1019. provide multiple initializations or incrementations.
  1020. .IP \(bu
  1021. Goto statements should be used sparingly as in any well-structured
  1022. code\*f.
  1023. .FS
  1024. .IP \*F
  1025. The \fIcontinue\fR statement is almost as bad.
  1026. \fIBreak\fR is less troublesome.
  1027. .FE
  1028. The main place where they can be usefully employed is to break out
  1029. of several levels of \fIswitch\fR, \fIfor\fR, and \fIwhile\fR
  1030. nesting\*f, e.g.
  1031. .FS
  1032. .IP \*F
  1033. The need to do such a thing may indicate
  1034. that the inner constructs should be broken out into
  1035. a separate function, with a success/failure return code.
  1036. .FE
  1037. .DS L
  1038.     for (...)
  1039.         for (...) {
  1040.             ...
  1041.             if (disaster)
  1042.                 goto error;
  1043.         }
  1044.     \&...
  1045. error:
  1046.     clean up the mess
  1047. .DE
  1048. When a \fIgoto\fR is necessary the accompanying label should be alone
  1049. on a line and tabbed one tab position to the left of the associated
  1050. code that follows.
  1051. .IP \(bu
  1052. This committee recommends that programmers not rely on automatic
  1053. beautifiers for the following reasons.
  1054. First, the main person who benefits from good program style is the
  1055. programmer himself.
  1056. This is especially true in the early design of handwritten algorithms
  1057. or pseudo-code.
  1058. Automatic beautifiers can only be applied to complete, syntactically
  1059. correct programs and hence are not available when the need for
  1060. attention to white space and indentation is greatest.
  1061. It is also felt that programmers can do a better job of making clear
  1062. the complete visual layout of a function or file, with the normal
  1063. attention to detail of a careful programmer\*f.
  1064. .FS
  1065. .IP \*F
  1066. In other words, some of the visual layout is dictated by intent
  1067. rather than syntax.
  1068. Beautifiers cannot read minds.
  1069. .FE
  1070. Sloppy programmers should learn to be careful programmers instead of
  1071. relying on a beautifier to make their code readable.
  1072. Finally, it is felt that since beautifiers are non-trivial programs
  1073. that must parse the source,
  1074. the burden of maintaining them in the face of the continuing evolution
  1075. of C is not worth the benefits gained by such a program.
  1076. .NH
  1077. Project Dependent Standards
  1078. .PP
  1079. Individual projects may wish to establish additional standards beyond
  1080. those given here.
  1081. The following issues are some of those that should be adddressed by
  1082. each project program administration group.
  1083. .IP \(bu
  1084. What additional naming conventions should be followed?
  1085. In particular, systematic prefix conventions for functional grouping
  1086. of global data and also for structure or union member names can be useful.
  1087. .IP \(bu
  1088. What kind of include file organization is appropriate for the
  1089. project's particular data hierarchy?
  1090. .IP \(bu
  1091. What procedures should be established for reviewing \fIlint\fR
  1092. complaints?
  1093. A tolerance level needs to be established in concert with the \fIlint\fR
  1094. options to prevent unimportant complaints from hiding complaints about
  1095. real bugs or inconsistencies.
  1096. .IP \(bu
  1097. If a project establishes its own archive libraries, it should plan on
  1098. supplying a lint library file [2] to the system administrators.
  1099. This will allow \fIlint\fR to check for compatible use of library
  1100. functions.
  1101. .NH
  1102. Conclusion
  1103. .PP
  1104. A set of standards has been presented for C programming style.
  1105. One of the most important points is the proper use of white space
  1106. and comments so that the structure of the program is evident from
  1107. the layout of the code.
  1108. Another good idea to keep in mind when writing code is that it is
  1109. likely that you or someone else will be asked to modify it or make
  1110. it run on a different machine sometime in the future.
  1111. .PP
  1112. As with any standard, it must be followed if it is to be useful.
  1113. The Indian Hill version of \fIlint\fR will enforce those standards
  1114. that are amenable to automatic checking.
  1115. If you have trouble following any of these standards don't just ignore them.
  1116. Programmers at Indian Hill should bring their problems to the
  1117. Software Development System Group (Lee Kirchhoff, contact) in department
  1118. 5522.
  1119. Programmers outside Indian Hill should contact the Processor
  1120. Application Group (Layne Cannon, contact) in department 5512\ \*f.
  1121. .FS
  1122. .IP \*F
  1123. At U of T Zoology, it's Henry Spencer in 336B.
  1124. .FE
  1125. .bp
  1126. .ce 1
  1127. \fBReferences\fR
  1128. .sp 2
  1129. .IP [1]
  1130. B.A. Tague, "C Language Portability", Sept 22, 1977.
  1131. This document issued by department 8234 contains three memos by
  1132. R.C. Haight, A.L. Glasser, and T.L. Lyon dealing with style and
  1133. portability.
  1134. .IP [2]
  1135. S.C. Johnson, "Lint, a C Program Checker", Technical Memorandum,
  1136. 77-1273-14, September 16, 1977.
  1137. .IP [3]
  1138. R.W. Mitze, "The 3B/PDP-11 Swabbing Problem", Memorandum for File,
  1139. 1273-770907.01MF,
  1140. September 14, 1977.
  1141. .IP [4]
  1142. R.A. Elliott and D.C. Pfeffer, "3B Processor Common Diagnostic
  1143. Standards- Version 1",
  1144. Memorandum for File, 5514-780330.01MF, March 30, 1978.
  1145. .IP [5]
  1146. R.W. Mitze,
  1147. "An Overview of C Compilation of UNIX User Processes on the 3B",
  1148. Memorandum for File, 5521-780329.02MF, March 29, 1978.
  1149. .IP [6]
  1150. B.W. Kernighan and D.M. Ritchie,
  1151. \fIThe C Programming Language\fR, 
  1152. Prentice-Hall 1978.
  1153. .bp
  1154. .PP
  1155. .DS L
  1156. .ta 8 16 24 32 40 48 56 64 72 80
  1157. /*
  1158.  * \fBThe C Style Summary Sheet\fR                Block comment,
  1159.  * by Henry Spencer, U of T Zoology            describes file.
  1160.  */
  1161.  
  1162. #include <errno.h>                    Headers; don't nest.
  1163.  
  1164. typedef int    SEQNO;    /* ... */            Global definitions.
  1165. #define    STREQ(a, b)    (strcmp((a), (b)) == 0)
  1166.  
  1167. static char *foo = NULL;    /* ... */        Global declarations.
  1168. struct bar {                        Static whenever poss.
  1169.     SEQNO alpha;    /* ... */
  1170. #        define    NOSEQNO    0
  1171.     int beta;    /* ... */            Don't assume 16 bits.
  1172. };
  1173.  
  1174. /*
  1175.  * Many unnecessary braces, to show where.        Functions.
  1176.  */
  1177. static int        /* what is returned */        Don't default int.
  1178. bletch(a)
  1179. int a;            /* ... */            Don't default int.
  1180. {
  1181.     int bar;        /* ... */
  1182.     extern int errno;    /* ..., changed here */
  1183.     extern char *index();
  1184.  
  1185.     if (foobar() != FAIL) {            if (!isvalid()) {
  1186.         return(OK);                errno = ERANGE;
  1187.     }                    } else {
  1188.                             x = &y + z\->field;
  1189.     while (x == (y & MASK)) {        }
  1190.         f += (x >= 0) ? x : \-x;
  1191.     }                    for (i = 0; i < BOUND; i++) {
  1192.                             /* lint \-h[p]cax. */
  1193.     do {                    }
  1194.         /* Avoid nesting ?: */
  1195.     } while (index(a, b) != NULL);        if (STREQ(x, "foo")) {
  1196.                             x |= 07;    /* 07 is... */
  1197.     switch (...) {                } else if (STREQ(x, "bar")) {
  1198.     case ABC:                    x &= ~077;    /* 077 is... */
  1199.     case DEF:                } else if (STREQ(x, "ugh")) {
  1200.         printf("...", a, b);            /* Avoid gotos */
  1201.         break;                } else {
  1202.     case XYZ:                    /* and continues. */
  1203.         x = y;                }
  1204.         /* FALLTHROUGH */
  1205.     default:                while ((c = getc()) != EOF)
  1206.         /* Limit imbedded =s. */        ;    /* NULLBODY */
  1207.         break;
  1208.     }
  1209. }
  1210. .DE
  1211. ---------------
  1212.  
  1213.  
  1214.