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 / C-Style-doc.ms.tbl.Z / C-Style-doc.ms.tbl
Encoding:
Text File  |  1992-10-18  |  98.1 KB  |  3,349 lines

  1. .\"
  2. .\" Version of Indian Hill Style Manual (U of T amended)
  3. .\" revision $Revision: 6.1 $
  4. .\"
  5. .\" make with  ``... | tbl | {{di,}t,n}roff -ms ..''
  6. .\" See the `.ds C C\"' macro, to set the C source code font.
  7. .\"
  8. .\" This document was really written with `troff' in mind.  You will
  9. .\" need to do significant hacking to get nice output with `nroff'.
  10. .\"
  11. .\" You may have comments, suggestions, bug fixes, etc.  Send them to
  12. .\" me and I will try to incorporate them (one way or another) in to
  13. .\" a future version.   If you change this document, please add a note
  14. .\" that it has been modified and change the minor version number
  15. .\" (e.g., version 5.0 becomes 5.1 or 5.0.zork, or whatever) and the
  16. .\" last date of modification (printed in the footer of each page).
  17. .\"
  18. .\" pardo@cs.washington.edu or
  19. .\" {rutgers,cornell,ucsd,ubc-cs,tektronix}!uw-beaver!june!pardo
  20. .\"
  21. .\"
  22. .\"--------------------
  23. .\" Footnote numbering
  24. .ds f \\u\s-2\\n+f\\s+2\d
  25. .nr f 0 1
  26. .ds F \\n+F.
  27. .nr F 0 1
  28. .\"--------------------
  29. .\" Select a font and a format for blocks of code.
  30. .\" If your system has fixed-width fonts, then that's
  31. .\" probably what you want to use.  If your system doesn't
  32. .\" support fixed-width fonts, then use the default.
  33. .\" Really aggressive hackers will want to use vgrind (grind).
  34. .\"
  35. .ds C C\"        \" Fixed-width font.  (`.ds C CW' if no C?)
  36. .\" `Ex': start example.
  37. .de Ex
  38. .DS \\$1
  39. .ft \*C
  40. .\" .DS \\$1        \" Use w/ any fixed-width font!
  41. .\" .ft \*C        \" Use fixed-width font.
  42. .\" .ft R        \" Default font if you don't have fixed-width.
  43. .\" .vS            \" Use vgrind.  (BROKE?)
  44. ..
  45. .\"
  46. .\" `Ee': end example.
  47. .de Ee
  48. .DE
  49. .\" .vE            \" End vgrind block.
  50. .\" .DE            \" One of the fonts.
  51. ..
  52. .\" Same idea, select a font for program text appearing `inline' in
  53. .\" the text.  use the same selection choices as for code blocks.
  54. .\" Prepend `\&' in case the trailing arg starts w/ a period.
  55. .\"
  56. .\" Usage:
  57. .\"    .Ec foo         (`foo' in code font)
  58. .\"    .Ec foo mp      (`foomp', `foo' in code font, `mp' not)
  59. .\"    .Ec foo mp ka   (`kafoomp', `foo' in code font, rest not)
  60. .\"
  61. .de Ep
  62. .nh
  63. \&\\$3\c
  64. .ft \*C
  65. \\$1\fP\\$2\"            fixed-width font (not broke...)
  66. .hy
  67. .\"\&\\$3\f\*C\\$1\fP\\$2\"    fixed-width font (BUG: BROKE!)
  68. .\"\&\\$3\fC\\$1\fP\\$2\"    fixed-width font
  69. .\" \&\\$3\fB\\$1\fP\\$2\"    default (general) font
  70. ..
  71. .\"    Same idea, select a font for `ideas' (concepts) that appear
  72. .\"    in the text.
  73. .de Ec
  74. \&\\$3\fI\\$1\fP\\$2
  75. ..
  76. .\"--------------------
  77. .\"
  78. .nr x \w'    '\" find width of 4 spaces.
  79. .ta \nxu +\nxu +\nxu +\nxu +\nxu +\nxu +\nxu +\nxu +\nxu  \" set tabs using that
  80. .\"
  81. .\"--------------------
  82. .\" Long digressionary comment:  There's lots of embedded junk that
  83. .\" acts as ``rationale'' for rules or explains something or is of
  84. .\" some interest, but of limited relevance.  Those embedded comments
  85. .\" might well be interesting to somebody, thus they should PERHAPS
  86. .\" optionally be
  87. .\"
  88. .\" (a) ignored (yes!)
  89. .\" (b) printed as endnotes
  90. .\" (c) printed as footnotes
  91. .\" (d) printed as inline text
  92. .\"
  93. .\" That is,
  94. .\"
  95. .\"     mumble, foo, bar, zork.
  96. .\"     .BS
  97. .\"     The zoop machine bit-aligns the user
  98. .\"     The foop machine byte-aligns the user.
  99. .\"     The boop machine floats the user right out the door.
  100. .\"     .ES
  101. .\"     Other sterling words of wisdom.
  102. .\"
  103. .\" So suppose that register `r' and macro/string `ZZ' are unused,
  104. .\" then reasonable macros include:
  105. .\"
  106. .\"     .de BS
  107. .\"     .if \\nr==0 .de ZZ ES
  108. .\"     .if \\nr==1 .BE
  109. .\"     .if \\nr==2 .FS
  110. .\"     ..
  111. .\"     .de ES
  112. .\"     .if \\nr==1 .EE
  113. .\"     .if \\nr==2 .FE
  114. .\"     ..
  115. .\"
  116. .\" Then, if register r is 0, everything from the .BS to the .ES will
  117. .\" become the definition of a macro ZZ, which are never read back;
  118. .\" thus it is effectively (and fairly efficiently) thrown away.
  119. .\"
  120. .\" If register r is 1, .BS invokes .BE, and .ES invokes .EE --
  121. .\" supposing .BE and .EE are names for macros for end-notes, though
  122. .\" such thing might not exist in the -ms macros.  IMHO, the various
  123. .\" comments shouldn't be end-nodes.  End-notes are for things like
  124. .\" "op. cit. pp. 6-42", never for actual commentary on the text; it's
  125. .\" just too much effort to read them.
  126. .\"
  127. .\" If register r is 2, .BS invokes .FS, and .ES invokes .FE; and
  128. .\" if register r has any other value, .BE and .ES do nothing at all,
  129. .\" so the material comes out inline.  (The text should probably be
  130. .\" blocked out with a `.QP' and a `\fBRemark:\fP or some such; see
  131. .\" Knuth's "dangerous bend" paragraphs in The TeXBook.)
  132. .\"
  133. .\" Using a register with a 1-character name because it works nicely
  134. .\" with troff's -r option.  With the above macros, doing nothing
  135. .\" makes the optional comments to disappear, -rr1 makes them in to
  136. .\" end-notes, -rr2 for footnotes, and -rr3 for inline text.
  137. .\"
  138. .\" It probably isn't a good idea to do all that, though.  People will
  139. .\" just get confused about versions.  Better to just include or
  140. .\" exclude the notes.
  141. .\"
  142. .\"----------------
  143. .RP
  144. .TL
  145. Recommended C Style and Coding Standards
  146. .AU
  147. L.W. Cannon
  148. R.A. Elliott
  149. L.W. Kirchhoff
  150. J.H. Miller
  151. J.M. Milner
  152. R.W. Mitze
  153. E.P. Schan
  154. N.O. Whittington
  155. .AI
  156. Bell Labs
  157. .AU
  158. Henry Spencer
  159. .AI
  160. Zoology Computer Systems
  161. University of Toronto
  162. .AU
  163. David Keppel
  164. .AI
  165. EECS, UC Berkeley
  166. CS&E, University of Washington
  167. .AU
  168. Mark Brader
  169. .AI
  170. SoftQuad Incorporated
  171. Toronto
  172. .AB
  173. This document is an updated version of the
  174. \fIIndian Hill C Style and Coding Standards\fP
  175. paper,
  176. with modifications by the last three authors.
  177. It describes a recommended coding standard for
  178. C
  179. programs.
  180. The scope is coding style, not functional organization.
  181. .AE
  182. .\"--------------------
  183. .\" Headers/footers must be in double quotes because most versions
  184. .\" of .OF, .OH, ... are BROKE.  (They work until you get 10 arguments
  185. .\" and then silently truncate...
  186. .\" revision $Revision: 6.1 $
  187. .\"
  188. .OF "'Recommended C Coding Standards'Revision: 6.0'25 June 1990'"
  189. .EF "'Recommended C Coding Standards'Revision: 6.0'25 June 1990'"
  190. .nr PO 1.25i
  191. .ta 0.5i 1.0i 1.5i 2.0i 2.5i 3.0i
  192. .\"--------------------
  193. .NH
  194. Introduction
  195. .PP
  196. This document
  197. is a modified version of a document from
  198. a committee formed at AT&T's Indian Hill labs to establish
  199. a common set of coding standards and recommendations for the
  200. Indian Hill community.
  201. .\"
  202. .\" old:
  203. .\"
  204. .\" The scope of this work is C coding style,
  205. .\" rather than the functional organization of programs
  206. .\" or general issues such as the use of \fIgoto\fPs.
  207. .\"
  208. The scope of this work is C coding style.
  209. Good style should encourage consistent layout, improve
  210. portability, and reduce errors.
  211. .\"
  212. .\" "It's simply a matter of style, and while there
  213. .\" are many wrong styles, there really isn't any
  214. .\" one right style."      -- Ray Butterworth
  215. .\"
  216. This work does not cover functional organization, or general
  217. issues such as the use of
  218. .Ec goto s.
  219. We\*f
  220. .FS
  221. .IP \*F
  222. The opinions in this document
  223. do not reflect the opinions of all authors.
  224. This is still an evolving document.
  225. Please send comments and suggestions to
  226. pardo@cs.washington.edu or
  227. {rutgers,cornell,ucsd,ubc-cs,tektronix}!uw-beaver!june!pardo
  228. .FE
  229. have tried to combine previous work [1,6,8] on C style into a uniform
  230. set of standards that should be appropriate for any project using C,
  231. although parts are biased towards particular systems.
  232. Of necessity, these standards cannot cover all situations.
  233. Experience and informed judgement count for much.
  234. Programmers who encounter unusual situations should
  235. consult either
  236. experienced C programmers or code written by experienced C
  237. programmers (preferably following these rules).
  238. .PP
  239. The standards in this document are not of themselves required, but
  240. individual institutions or groups may adopt part or all of them
  241. as a part of program acceptance.
  242. It is therefore likely that others at your institution will code in
  243. a similar style.
  244. Ultimately, the goal of these standards is to
  245. increase portability, reduce maintenance, and above all
  246. improve clarity.
  247. .PP
  248. Many of the style choices here are somewhat arbitrary.
  249. Mixed coding style is harder to maintain than bad coding style.
  250. When changing existing code it is better to conform to the
  251. style (indentation, spacing, commenting, naming conventions)
  252. of the existing code than it is to blindly follow this document.
  253. .QP
  254. ``\fITo be clear is professional; not to be clear
  255. is unprofessional.\fP'' \(em Sir Ernest Gowers.
  256. .NH
  257. File Organization
  258. .PP
  259. A file consists of various sections that should be separated by
  260. several blank lines.
  261. Although there is no maximum length limit for source files,
  262. files with more than about 1000 lines are cumbersome to deal with.
  263. The editor may not have enough temp space to edit the file,
  264. compilations will go more slowly,
  265. etc.
  266. Many rows of asterisks, for example,
  267. present little information compared to the time it takes to scroll past,
  268. and are discouraged.
  269. Lines longer than 79 columns are not handled well by all terminals
  270. and should be avoided if possible.
  271. Excessively long lines which result from deep indenting are often
  272. a symptom of poorly-organized code.
  273. .NH 2
  274. File Naming Conventions
  275. .PP
  276. File names are made up of a base name,
  277. and an optional period and suffix.
  278. The first character of the name should be a letter
  279. and all characters (except the period)
  280. should be lower-case letters and numbers.
  281. The base name should be eight or fewer characters and the
  282. suffix should be three or fewer characters
  283. (four, if you include the period).
  284. These rules apply to both program files and
  285. default files used and produced by the program
  286. (e.g., ``rogue.sav'').
  287. .\"
  288. .\" 8 + 1 + 3 + ",v" fits RCS into Version 7 filesystems.
  289. .\" MS-DOS does 8 + "." + 3.
  290. .\"
  291. .PP
  292. Some compilers and tools require certain suffix conventions for names
  293. of files [5].
  294. The following suffixes are required:
  295. .IP \0\0\(bu
  296. C source file names must end in \fI.c\fP
  297. .IP \0\0\(bu
  298. Assembler source file names must end in \fI.s\fP
  299. .LP
  300. The following conventions are universally followed:
  301. .IP \0\0\(bu
  302. Relocatable object file names end in \fI.o\fP
  303. .IP \0\0\(bu
  304. Include header file names end in \fI.h\fP.
  305. .\"
  306. .\" \*f.
  307. .\" .FS
  308. .\" .IP \*F
  309. .\"
  310. An alternate convention that may
  311. be preferable in multi-language environments
  312. is to suffix both the language type and \fI.h\fP
  313. (e.g. ``foo.c.h'' or ``foo.ch'').
  314. .FE
  315. .IP \0\0\(bu
  316. Yacc source file names end in \fI.y\fP
  317. .IP \0\0\(bu
  318. Lex source file names end in \fI.l\fP
  319. .PP
  320. C++ has compiler-dependent suffix conventions,
  321. including \fI.c\fP, \fI..c\fP, \fI.cc\fP, \fI.c.c\fP, and \fI.C\fP.
  322. Since much C code is also C++ code, there is no clear solution here.
  323. .PP
  324. In addition,
  325. it is conventional to use ``Makefile'' (not ``makefile'') for the
  326. control file for \fImake\fP (for systems that support it)
  327. and ``README'' for a summary of the contents
  328. of the directory or directory tree.
  329. .\"
  330. .\" Having ``README'' in caps breaks the "monocase" rule, but is
  331. .\" convention.  Same for ``Makefile''.
  332. .\"
  333. .NH 2
  334. Program Files
  335. .PP
  336. The suggested order of sections for a program file is as follows:
  337. .IP 1.
  338. First in the file is a prologue that tells what is in that file.
  339. A description of the purpose of the objects in the files (whether
  340. they be functions, external data declarations or definitions, or
  341. something else) is more useful than a list of the object names.
  342. The prologue may optionally contain author(s),
  343. revision control information, references, etc.
  344. .IP 2.
  345. Any header file includes should be next.
  346. If the include is for a non-obvious reason,
  347. the reason should be commented.
  348. In most cases, system include files like \fIstdio.h\fP should be
  349. included before user include files.
  350. .IP 3.
  351. Any defines and typedefs that apply to the file as a whole are next.
  352. One normal order is to have
  353. ``constant'' macros first,
  354. then ``function'' macros, then typedefs and enums.
  355. .IP 4.
  356. Next come the global (external) data declarations,
  357. usually in the order: externs, non-static globals, static globals.
  358. If a set of defines applies to a particular piece of global data
  359. (such as a flags word), the defines should be immediately after
  360. the data declaration or embedded in structure declarations,
  361. indented to put the defines one level
  362. deeper than the first keyword of the declaration to which they apply.
  363. .IP 5.
  364. The functions come last,
  365. and should be in some sort of meaningful order.
  366. Like functions should appear together.
  367. A ``breadth-first''
  368. approach (functions on a similar level of abstraction together) is
  369. preferred over depth-first (functions defined as soon as possible
  370. before or after their calls).
  371. Considerable judgement is called for here.
  372. If defining large numbers of essentially-independent utility
  373. functions, consider alphabetical order.
  374. .NH 2
  375. Header Files
  376. .PP
  377. Header files are files that are included in other files prior to
  378. compilation by the C preprocessor.
  379. Some, such as \fIstdio.h\fP, are defined at the system level
  380. and must included by any program using the standard I/O library.
  381. Header files are also used to contain data declarations and defines
  382. that are needed by more than one program.
  383. Header files should be functionally organized,
  384. i.e., declarations for separate subsystems
  385. should be in separate header files.
  386. Also, if a set of declarations is likely to change when code is
  387. ported from one machine to another, those declarations should be
  388. in a separate header file.
  389. .PP
  390. Avoid private header filenames that are the same
  391. as library header filenames.
  392. The statement
  393. .Ep #include
  394. .Ep """math.h"""
  395. .\"
  396. .\" Or try .Ep math.h """" """"
  397. .\"
  398. will include the standard library math header file
  399. if the intended one is not
  400. found in the current directory.
  401. If this is what you \fIwant\fP to happen,
  402. comment this fact.
  403. Don't use absolute pathnames for header files.
  404. Use the
  405. .Ec <name>
  406. construction for getting them from a standard
  407. place, or define them relative to the current directory.
  408. The ``include-path'' option of the C compiler
  409. (\-I on many systems)
  410. is the best way to handle
  411. extensive private libraries of header files;  it permits reorganizing
  412. the directory structure without having to alter source files.
  413. .PP
  414. Header files that declare functions or external variables should be
  415. included in the file that defines the function or variable.
  416. That way, the compiler can do type checking and the external
  417. declaration will always agree with the definition.
  418. .PP
  419. Defining variables in a header file is often a poor idea.
  420. Frequently it is a symptom of poor partitioning of code between files.
  421. Also, some objects like typedefs and initialized data definitions
  422. cannot be seen twice by the compiler in one compilation.
  423. On some systems, repeating uninitialized declarations
  424. without the \fIextern\fP keyword also causes problems.
  425. Repeated declarations can happen if include files are nested
  426. and will cause the compilation to fail.
  427. .PP
  428. Header files should not be nested.
  429. .\"
  430. .\" Many people disagree strongly with this.
  431. .\" However, if you are to use \fIone\fP style, then this is best.
  432. .\" The #ifndef/#define/.../#endif approach (below) often causes
  433. .\" compilations to go much slower.
  434. .\" A #endinput directive would be nice.
  435. .\"
  436. The prologue for a header file should, therefore, describe what
  437. other headers need to be #included for the header to be functional.
  438. In extreme cases, where a large number of header files are to be
  439. included in several different source files,
  440. it is acceptable to put all common #includes in one include file.
  441. .PP
  442. It is common to put the following into each
  443. .Ec .h
  444. file
  445. to prevent accidental double-inclusion.
  446. .Ex
  447. #ifndef EXAMPLE_H
  448. #define EXAMPLE_H
  449. \&...    \fI/* body of example.h file */\fP
  450. #endif /* EXAMPLE_H */
  451. .Ee
  452. .LP
  453. This double-inclusion mechanism should not be relied upon,
  454. particularly to perform nested includes.
  455. .NH 2
  456. Other Files
  457. .PP
  458. It is conventional to have a file called ``README'' to document both
  459. ``the bigger picture'' and issues for the program as a whole.
  460. For example, it is common to include a list of all conditional
  461. compilation flags and what they mean.
  462. It is also common to list files that are machine dependent, etc.
  463. .NH
  464. Comments
  465. .QP
  466. .ad r
  467. ``\fIWhen the code and the comments disagree,
  468. both are probably wrong.\fP'' \(em Norm Schryer
  469. .\" \fIBumper-Sticker Computer Science\fP,
  470. .\" Jon Bently's \fIProgramming Pearls\fP column,
  471. .\" Communications of the ACM (CACM),
  472. .\" September 1985, Volume 28, Number 9.
  473. .\"
  474. .\" ``\fIMany's the time when I've thanked the Doug A. Gwyn of past
  475. .\" years for anticipating future maintenance questions and providing
  476. .\" helpful information in the original sources.\fP'' \(em Doug A.
  477. .\" Gwyn
  478. .\"
  479. .br
  480. .ad b
  481. .PP
  482. The comments should describe \fIwhat\fP is happening,
  483. \fIhow\fP it is being done,
  484. what parameters mean,
  485. .\"
  486. .\" BUG:
  487. .\" By X3.159-1989, ``formal parameters'' are called `parameters' and
  488. .\" ``actual parameters'' are called `arguments'.  A somewhat relaxed
  489. .\" form lets us call anything an argument, but only some formal
  490. .\" parameters are `parameters'.
  491. .\" The two usages are used inconsistantly in this document.
  492. .\"
  493. which globals are used and which are modified,
  494. and any restrictions or bugs.
  495. Avoid, however, comments that are clear from the code,
  496. as such information rapidly gets out of date.
  497. Comments that disagree with the code are of negative value.
  498. Short comments should be
  499. \fIwhat\fP comments, such as ``compute mean value'',
  500. rather than \fIhow\fP comments such as
  501. ``sum of values divided by n''.
  502. C is not assembler;
  503. putting a comment at the top of a 3\-10 line section telling what it
  504. does overall is often more useful than a comment on each line
  505. describing micrologic.
  506. .PP
  507. Comments should justify offensive code.
  508. The justification should be that something bad will happen if
  509. unoffensive code is used.
  510. Just making code faster is not enough to rationalize a hack;
  511. the performance must be \fIshown\fP to be unacceptable
  512. without the hack.
  513. The comment should explain the unacceptable behavior and describe why
  514. the hack is a ``good'' fix.
  515. .PP
  516. Comments that describe data structures, algorithms, etc., should be
  517. in block comment form with the opening
  518. .Ep /*
  519. in columns 1-2, a
  520. .Ep *
  521. in column 2 before each line of comment text,
  522. and the closing
  523. .Ep */
  524. in columns 2-3.
  525. An alternative is to have
  526. .Ep **
  527. in columns 1-2, and put the closing
  528. .Ep */
  529. also in 1-2.
  530. .Ex L
  531. /*
  532.  *    Here is a block comment.
  533.  *    The comment text should be tabbed or spaced over uniformly.
  534.  *    The opening slash-star and closing star-slash are alone on a line.
  535.  */
  536. .Ee
  537. .Ex L
  538. /*
  539. ** Alternate format for block comments
  540. */
  541. .Ee
  542. .PP
  543. Note that \fIgrep '^.\e*'\fP will catch all block comments in the
  544. file\*f.
  545. .FS
  546. .IP \*F
  547. Some automated program-analysis
  548. packages use different characters before comment lines as
  549. a marker for lines with specific items of information.
  550. In particular, a line with a
  551. .Ep \- ' `
  552. in a comment preceding a function
  553. is sometimes assumed to be a one-line summary of the function's
  554. purpose.
  555. .FE
  556. Very long block comments such as drawn-out discussions and copyright
  557. notices often start with
  558. .Ep /*
  559. in columns 1-2, no leading
  560. .Ep *
  561. before lines of text, and the closing
  562. .Ep */
  563. in columns 1-2.
  564. Block comments inside a function are appropriate, and
  565. they should be tabbed over to the same tab setting as the code that
  566. they describe.
  567. One-line comments alone on a line should be indented to the tab
  568. setting of the code that follows.
  569. .Ex
  570. if (argc > 1) {
  571.     /* Get input file from command line. */
  572.     if (freopen(argv[1], "r", stdin) =\^= NULL) {
  573.         perror (argv[1]);
  574.     }
  575. }
  576. .Ee
  577. .PP
  578. Very short comments may appear on the same line as the code they
  579. describe,
  580. and should be tabbed over to separate them from the statements.
  581. If more than one short comment appears in a block of code
  582. they should all be tabbed to the same tab setting.
  583. .Ex
  584. if (a =\^= EXCEPTION) {
  585.     b = TRUE;                /* special case */
  586. } else {
  587.     b = isprime(a);            /* works only for odd a */
  588. }
  589. .Ee
  590. .NH
  591. Declarations
  592. .PP
  593. Global declarations should begin in column 1.
  594. All external data declaration should be preceded by the
  595. .Ec extern
  596. keyword.
  597. If an external variable is an array that is defined with an explicit
  598. size, then the array bounds must be repeated in the extern
  599. declaration unless the size is always encoded in the array
  600. (e.g., a read-only character array that is always null-terminated).
  601. Repeated size declarations are
  602. particularly beneficial to someone picking up code written by another.
  603. .\"
  604. .\" /* foo.h */
  605. .\" #define SIZE 1234
  606. .\" extern int zork[SIZE];    /* ... and not `extern int zork[];' */
  607. .\"
  608. .\" /* foo.c */
  609. .\" int zork[SIZE];
  610. .\"
  611. .PP
  612. The ``pointer'' qualifier,
  613. .Ep * ', `
  614. should be with the variable name rather
  615. than with the type.
  616. .Ex
  617. char        *s, *t, *u;
  618. .Ee
  619. instead of
  620. .Ex
  621. char*    s, t, u;
  622. .Ee
  623. which is wrong, since
  624. .Ep t ' `
  625. and
  626. .Ep u ' `
  627. do not get declared as pointers.
  628. .PP
  629. Unrelated declarations, even of the same type,
  630. should be on separate lines.
  631. A comment describing the role of the object being declared should be
  632. included, with the exception
  633. that a list of
  634. .Ec #define d
  635. constants do not need comments
  636. if the constant names are sufficient documentation.
  637. The names, values, and comments
  638. are usually
  639. .\" should be
  640. tabbed so that they line up underneath each other.
  641. Use the tab character rather than blanks (spaces).
  642. For structure and union template declarations,
  643. each element should be alone on a line
  644. with a comment describing it.
  645. The opening brace
  646. .Ep { \^\^) (\^
  647. should be on the same line as the structure
  648. tag, and the closing brace
  649. .Ep } \^) (\^\^
  650. should be in column 1.
  651. .Ex
  652. struct boat {
  653.     int        wllength;    /* water line length in meters */
  654.     int        type;        /* see below */
  655.     long        sailarea;    /* sail area in square mm */
  656. };
  657.  
  658. /* defines for boat.type */
  659. #define    KETCH    (1)
  660. #define    YAWL        (2)
  661. #define    SLOOP    (3)
  662. #define    SQRIG    (4)
  663. #define    MOTOR    (5)
  664. .Ee
  665. .\"
  666. .\" If this formatting `loses', you can probably fix it, but you'll
  667. .\" have to be careful about tabs that appear later.
  668. .\"
  669. .\" .\" Set up a tab field, with the worst-case tabbing, more or less
  670. .\" .ta \w'MOTOR    'u
  671. .\" .\" #define KETCH<tab>1 (etc.)
  672. .\"
  673. .LP
  674. These defines are sometimes put right after the declaration of
  675. .Ep type ,
  676. within the
  677. .Ep struct
  678. declaration, with enough tabs after the
  679. .Ep # \^' `
  680. to indent
  681. .Ep define
  682. one level more than the structure member declarations.
  683. When the actual values are unimportant,
  684. the
  685. .Ec enum
  686. facility is better\*f.
  687. .FS
  688. .IP \*F
  689. .Ec enum s
  690. might be better anyway.
  691. .FE
  692. .Ex
  693. enum bt { KETCH=1, YAWL, SLOOP, SQRIG, MOTOR };
  694. struct boat {
  695.     int        wllength;    /* water line length in meters */
  696.     enum bt    type;        /* what kind of boat */
  697.     long        sailarea;    /* sail area in square mm */
  698. };
  699. .Ee
  700. .PP
  701. Any variable whose initial value is important should be
  702. \fIexplicitly\fP initialized, or at the very least should be commented
  703. to indicate that C's default initialization to zero
  704. is being relied upon.
  705. The empty initializer,
  706. .Ep {\^} '', ``
  707. should never be used.
  708. Structure
  709. initializations should be fully parenthesized with braces.
  710. .\"
  711. .\" Consider the following:
  712. .\"
  713. .\" struct foo {int i, j};
  714. .\" struct foo bar[] = {1, 2, 3, 4};
  715. .\" struct foo kung[] = {{1, 2}, {3, 4}};
  716. .\" struct foo oh[] = {};
  717. .\"
  718. .\" `bar' is accepted, but is visually ambiguous.
  719. .\" `oh' is also accepted.  Don't do it -- what does it mean?
  720. .\"
  721. .\" The following is NOT ambiguous and is good style.
  722. .\"
  723. .\" struct foo kung[] = {{1}, {3}};
  724. .\"
  725. Constants used to initialize longs should be explicitly long.
  726. Use capital letters; for example two long
  727. .Ep 2l '' ``
  728. looks a lot like
  729. .Ep 21 '', ``
  730. the number twenty-one.
  731. .Ex
  732. int        x = 1;
  733. char        *msg = "message";
  734. struct boat    winner[] = {
  735.     { 40, YAWL, 6000000L },
  736.     { 28, MOTOR, 0L },
  737.     { 0 },
  738. };
  739. .Ee
  740. .PP
  741. In any file which is part of a larger whole rather than a self-contained
  742. program, maximum use should be made of the
  743. .Ec static
  744. keyword to make functions and variables local to single files.
  745. Variables in particular should be accessible from other files
  746. only when there is a clear
  747. need that cannot be filled in another way.
  748. Such usage should be commented to make it clear that another file's
  749. variables are being used; the comment should name the other file.
  750. If your debugger hides static objects you need to see during
  751. debugging,
  752. declare them as
  753. .Ep STATIC
  754. and #define
  755. .Ep STATIC
  756. as needed.
  757. .PP
  758. The most important types should be highlighted by typedeffing
  759. them, even if they are only integers,
  760. as the unique name makes the program easier to read (as long as there
  761. are only a \fIfew\fP things typedeffed to integers!).
  762. Structures may be typedeffed when they are declared.
  763. Give the struct and the typedef the same name.
  764. .Ex
  765. typedef struct splodge_t {
  766.     int    sp_count;
  767.     char    *sp_name, *sp_alias;
  768. } splodge_t;
  769. .Ee
  770. .PP
  771. The return type of functions should always be declared.
  772. If function prototypes are available, use them.
  773. One common mistake is to omit the
  774. declaration of external math functions that return
  775. .Ec double .
  776. The compiler then assumes that
  777. the return value is an integer and the bits are dutifully
  778. converted into a (meaningless) floating point value.
  779. .QP
  780. .ce
  781. ``\fIC takes the point of view that the programmer is always right.\fP'' \(em Michael DeCorte
  782. .NH
  783. Function Declarations
  784. .PP
  785. Each function should be preceded by a block comment prologue
  786. that gives a short description of what the function does
  787. and (if not clear) how to use it.
  788. Discussion of non-trivial design decisions and
  789. side-effects is also appropriate.
  790. Avoid duplicating information clear from the code.
  791. .PP
  792. The function return type should be alone on a line,
  793. (optionally) indented one stop\*f.
  794. .FS
  795. .IP \*F
  796. ``Tabstops'' can be blanks (spaces) inserted by your editor in clumps
  797. of 2, 4, or 8.
  798. Use actual tabs where possible.
  799. .FE
  800. Do not default to
  801. .Ec int ;
  802. if the function does not return a value then it should be given
  803. return type \fIvoid\fP\*f.
  804. .FS
  805. .IP \*F
  806. .Ep "#define"
  807. .Ep void
  808. or
  809. .Ep "#define"
  810. .Ep void
  811. .Ep int
  812. for compilers without the
  813. .Ec void
  814. keyword.
  815. .FE
  816. If the value returned requires a long explanation,
  817. it should be given in the prologue;
  818. otherwise it can be on the same line as the return type, tabbed over.
  819. The function name
  820. (and the formal parameter list)
  821. should be alone on a line, in column 1.
  822. Destination (return value) parameters
  823. should generally be first (on the left).
  824. All formal parameter declarations,
  825. local declarations and code within the function body
  826. should be tabbed over one stop.
  827. The opening brace of the function body should be alone on a line
  828. beginning in column 1.
  829. .PP
  830. Each parameter should be declared (do not default to
  831. .Ec int ).
  832. In general the role of each variable in the function should be described.
  833. This may either be done in the function comment or, if each declaration
  834. is on its own line, in a comment on that line.
  835. Loop counters called ``i'',  string pointers called ``s'',
  836. and integral types called ``c'' and used for characters
  837. are typically excluded.
  838. If a group of functions all have a like parameter or local variable,
  839. it helps to call the repeated variable by the same name in all
  840. functions.
  841. (Conversely, avoid using the same name for different purposes in
  842. related functions.)
  843. Like parameters should also appear in the same place in the various
  844. argument lists.
  845. .PP
  846. Comments for parameters and local variables should be
  847. tabbed so that they line up underneath each other.
  848. Local variable declarations should be separated
  849. from the function's statements by a blank line.
  850. .\"
  851. .\"    int zork;            /* Last known zork. */
  852. .\"    struct price_tag inventory[MAX_STORES][MAX_STOCK]
  853. .\"                    /* Corporate structure. */
  854. .\"    some_really_long_type_name *tree;
  855. .\"                    /* root of the parse tree */
  856. .\"    char *s;            /* variable name */
  857. .\"
  858. .\" If a variable has an extremely long definition, the comment
  859. .\" should come \fIafter\fP the declaration.  Multiline comments
  860. .\" for variables should be moved to the header and referenced
  861. .\" from the comment.
  862. .\"
  863. .\"    * Note 1: The variable `zork' has two lives.  It first ...
  864. .\"    */
  865. .\"
  866. .\"        void *zork;        /* See header note #1. */
  867. .\"
  868. .PP
  869. Be careful when you use or declare functions
  870. that take a variable number of arguments (``varargs'').
  871. There is no truly portable way to do varargs in C.
  872. Better to design an interface that uses a fixed number of arguments.
  873. If you must have varargs,
  874. use the library macros for declaring functions with
  875. variant argument lists.
  876. .PP
  877. If the function uses any external variables (or functions)
  878. that are not declared globally in the file,
  879. these should have their
  880. own declarations in the function body using the
  881. .Ec extern
  882. keyword.
  883. .PP
  884. Avoid local declarations that override declarations at higher levels.
  885. In particular, local variables
  886. should not be redeclared in nested blocks.
  887. Although this is valid C, the potential confusion is
  888. enough that
  889. \fIlint\fP will complain about it when given the \-h option.
  890. .NH
  891. Whitespace
  892. .QP
  893. .ad r
  894. \fIint i;main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\\
  895. .br
  896. o, world!\\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);}\fP
  897. .br
  898. \(em Dishonorable mention, Obfuscated C Code Contest, 1984.
  899. .br
  900. Author requested anonymity.
  901. .br
  902. .ad b
  903. .PP
  904. .\"Use whitespace generously, both vertically and horizontally.
  905. Use vertical and horizontal whitespace generously.
  906. Indentation and spacing should reflect the block structure of the code;
  907. e.g.,
  908. there should be at least 2 blank lines between the end of one function
  909. and the comments for the next.
  910. .PP
  911. A long string of conditional operators should be split
  912. onto separate lines.
  913. .Ex
  914. if (foo->next=\^=NULL && totalcount<needed && needed<=MAX_ALLOT
  915.     && server_active(current_input)) { ...
  916. .Ee
  917. Might be better as
  918. .Ex
  919. if (foo->next =\^= NULL
  920.     && totalcount < needed && needed <= MAX_ALLOT
  921.     && server_active(current_input))
  922. {
  923.     ...
  924. .Ee
  925. Similarly, elaborate
  926. .Ec for
  927. loops should be split onto different lines.
  928. .Ex
  929. for (curr = *listp, trail = listp;
  930.     curr != NULL;
  931.     trail = &(curr->next), curr = curr->next )
  932. {
  933. \&    ...
  934. .Ee
  935. Other complex expressions, particularly those using the ternary
  936. .Ec ?\^:
  937. operator,
  938. are best split on to several lines, too.
  939. .Ex
  940. c = (a == b)
  941.     ? d + f(a)
  942.     : f(b) - d;
  943. .Ee
  944. .\" .PP
  945. .\" Finally, the closing brace of long functions and very long blocks
  946. .\" should include an ``end function'' or ``end block'' comment:
  947. .\" .DS
  948. .\" \&    }    /* end  for (each list element) */
  949. .\" \&    ...
  950. .\" }    /* end function_name() */
  951. .Ee
  952. Keywords that are followed by expressions in parentheses
  953. should be separated from the left parenthesis by a blank.
  954. (The
  955. .Ec sizeof
  956. operator is an exception.)
  957. .\"
  958. .\" Because `sizeof' is an OPERATOR.
  959. .\"
  960. Blanks should also appear after commas in argument lists to help
  961. separate the arguments visually.
  962. On the other hand, macro definitions with arguments must
  963. not have a blank between the name and the left parenthesis,
  964. otherwise the C preprocessor will not recognize the argument list.
  965. .\"
  966. .\" The C preprocessor requires the left parenthesis,
  967. .\" to be immediately after the macro name or else the argument list
  968. .\" will not be recognized.
  969. .\"
  970. .NH
  971. Examples
  972. .\"
  973. .\" Perhaps this should be a complete file?
  974. .\"
  975. .PP
  976. .Ex
  977. /*
  978.  *    Determine if the sky is blue by checking that it isn't night.
  979.  *    CAVEAT: Only sometimes right.  May return TRUE when the answer
  980.  *    is FALSE.  Consider clouds, eclipses, short days.
  981.  *    NOTE: Uses `hour' from `hightime.c'.  Returns `int' for
  982.  *    compatibility with the old version.
  983.  */
  984.     int                        /* true or false */
  985. skyblue()
  986. {
  987.     extern int    hour;        /* current hour of the day */
  988.  
  989.     return (hour >= MORNING && hour <= EVENING);
  990. }
  991. .Ee
  992. .Ex
  993. /*
  994.  *    Find the last element in the linked list
  995.  *    pointed to by nodep and return a pointer to it.
  996.  *    Return NULL if there is no last element.
  997.  */
  998.     node_t *
  999. tail(nodep)
  1000.     node_t    *nodep;            /* pointer to head of list */
  1001. {
  1002.     register node_t    *np;        /* advances to NULL */
  1003.     register node_t    *lp;        /* follows one behind np */
  1004.  
  1005.     if (nodep =\^= NULL)
  1006.         return (NULL);
  1007.     for (np = lp = nodep; np != NULL; lp = np, np = np->next)
  1008.         ;    /* VOID */
  1009.     return (lp);
  1010. }
  1011. .Ee
  1012. .NH
  1013. Simple Statements
  1014. .PP
  1015. There should be only one statement per line unless the statements are
  1016. very closely related.
  1017. .Ex
  1018. case FOO:      oogle (zork);  boogle (zork);  break;
  1019. case BAR:      oogle (bork);  boogle (zork);  break;
  1020. case BAZ:      oogle (gork);  boogle (bork);  break;
  1021. .Ee
  1022. The null body of a
  1023. .Ec for
  1024. or
  1025. .Ec while
  1026. loop should be alone on a line and commented
  1027. so that it is clear that the null body is intentional
  1028. and not missing code.
  1029. .Ex
  1030. while (*dest++ = *src++)
  1031.     ;    /* VOID */
  1032. .Ee
  1033. .\"
  1034. .\" An alternative convention is to use
  1035. .\" .Ep continue
  1036. .\" explicitly.
  1037. .\" .Ex
  1038. .\" while (*dest++ = *src++)
  1039. .\"    continue;
  1040. .\" .Ee
  1041. .\"
  1042. .PP
  1043. Do not default the test for non-zero, i.e.
  1044. .Ex
  1045. if (f(\^) != FAIL)
  1046. .Ee
  1047. is better than
  1048. .Ex
  1049. if (f(\^))
  1050. .Ee
  1051. even though
  1052. .Ep FAIL
  1053. may have the value 0 which C considers to be false.
  1054. An explicit test will help you out later when somebody decides that a
  1055. failure return should be \-1 instead of 0.
  1056. Explicit comparison should be used even if the comparison value will
  1057. never change; e.g., 
  1058. .Ep "if (!(bufsize % sizeof(int)))" '' ``
  1059. should be written instead as
  1060. .Ep "if ((bufsize % sizeof(int)) =\^= 0)" '' ``
  1061. to reflect the \fInumeric\fP (not \fIboolean\fP) nature of the test.
  1062. A frequent trouble spot is using
  1063. .Ep strcmp
  1064. to test for string equality, where the result should \fInever\fP
  1065. \fIever\fP be defaulted.
  1066. The preferred approach is to define a macro \fISTREQ\fP.
  1067. .Ex
  1068. #define STREQ(a, b) (strcmp((a), (b)) =\^= 0)
  1069. .Ee
  1070. .PP
  1071. The non-zero test \fIis\fP often defaulted for predicates
  1072. and other functions or expressions which meet the following
  1073. restrictions:
  1074. .IP \0\0\(bu
  1075. Evaluates to 0 for false, nothing else.
  1076. .IP \0\0\(bu
  1077. Is named so that the meaning of (say) a `true' return
  1078. is absolutely obvious.
  1079. Call a predicate \fIisvalid\fP or \fIvalid\fP, not \fIcheckvalid\fP.
  1080. .\"
  1081. .\" The non-zero test is also defaulted for NULL pointer checks,
  1082. .\" e.g.,
  1083. .\" .Ep "p = malloc(n); if (!p) error()" ''. ``
  1084. .\" It is defaulted because essentually you are saying ``allocate `p'.
  1085. .\" If no `p', then error.''
  1086. .\" (Thus, it is covered by the existing rules.)
  1087. .\"
  1088. .PP
  1089. It is common practice to declare a boolean type
  1090. .Ep bool '' ``
  1091. in a global include file.
  1092. .\"
  1093. .\" Unfortunately, the ideal type to use may differ for scalar and
  1094. .\" array variables.
  1095. .\"
  1096. The special names improve readability immensely.
  1097. .Ex
  1098. typedef int    bool;
  1099. #define FALSE    0
  1100. #define TRUE    1
  1101. .Ee
  1102. or
  1103. .Ex
  1104. typedef enum { NO=0, YES } bool;
  1105. .Ee
  1106. .LP
  1107. Even with these declarations,
  1108. do not check a boolean value for equality with 1 (TRUE, YES, etc.);
  1109. instead test for inequality with 0 (FALSE, NO, etc.).
  1110. Most functions are guaranteed to return 0 if false,
  1111. but only non-zero if true.
  1112. Thus,
  1113. .Ex
  1114. if (func() =\^= TRUE) { ...
  1115. .Ee
  1116. must be written
  1117. .Ex
  1118. if (func() != FALSE) { ...
  1119. .Ee
  1120. It is even better (where possible) to rename the function/variable or
  1121. rewrite the expression so that the meaning is obvious without a
  1122. comparison to true or false
  1123. (e.g., rename to \fIisvalid()\fP).
  1124. .PP
  1125. There is a time and a place for embedded assignment statements.
  1126. In some constructs there is no better way to accomplish the results
  1127. without making the code bulkier and less readable.
  1128. .Ex
  1129. while ((c = getchar()) != EOF) {
  1130.     process the character
  1131. }
  1132. .Ee
  1133. The
  1134. .Ep ++
  1135. and
  1136. .Ep \-\^\^\-
  1137. operators count as assignment statements.
  1138. So, for many purposes, do functions with side effects.
  1139. Using embedded assignment statements to improve run-time performance
  1140. is also possible.
  1141. However, one should consider the tradeoff between increased speed and
  1142. decreased maintainability that results when embedded assignments are
  1143. used in artificial places.
  1144. For example,
  1145. .Ex
  1146. a = b + c;
  1147. d = a + r;
  1148. .Ee
  1149. should not be replaced by
  1150. .Ex
  1151. d = (a = b + c) + r;
  1152. .Ee
  1153. even though the latter may save one cycle.
  1154. In the long run the time difference between the two will
  1155. decrease as the optimizer gains maturity, while the difference in
  1156. ease of maintenance will increase as the human memory of what's
  1157. going on in the latter piece of code begins to fade.
  1158. .PP
  1159. Goto statements should be used sparingly, as in any well-structured
  1160. code.
  1161. The main place where they can be usefully employed is to break out
  1162. of several levels of
  1163. .Ec switch ,
  1164. .Ec for ,
  1165. and
  1166. .Ec while
  1167. nesting,
  1168. although the need to do such a thing may indicate
  1169. that the inner constructs should be broken out into
  1170. a separate function, with a success/failure return code.
  1171. .Ex
  1172.     for (...) {
  1173.         while (...) {
  1174.             ...
  1175.             if (disaster)
  1176.                 goto error;
  1177.         
  1178.         }
  1179.     }
  1180.     \&...
  1181. error:
  1182.     clean up the mess
  1183. .Ee
  1184. When a
  1185. .Ec goto
  1186. is necessary the accompanying label should be alone
  1187. on a line and tabbed one stop to the left of the
  1188. code that follows.
  1189. The goto should be commented (possibly in the block header)
  1190. as to its utility and purpose.
  1191. .Ec Continue
  1192. should be used sparingly and near the top of the loop.
  1193. .Ec Break
  1194. is less troublesome.
  1195. .PP
  1196. Parameters to non-prototyped functions sometimes need to be promoted
  1197. explicitly.
  1198. If, for example, a function expects a 32-bit
  1199. .Ec long
  1200. and gets handed a 16-bit
  1201. .Ec int
  1202. instead,
  1203. the stack can get misaligned.
  1204. Problems occur with pointer, integral, and floating-point values.
  1205. .NH
  1206. Compound Statements
  1207. .PP
  1208. A compound statement is a list of statements enclosed by braces.
  1209. There are many common ways of formatting the braces.
  1210. Be consistent with your local standard, if you have one,
  1211. or pick one and use it consistently.
  1212. When editing someone else's code, \fIalways\fP use the style
  1213. used in that code.
  1214. .Ex
  1215. control {
  1216. \ \ \ \ \ \ \ \ statement;
  1217. \ \ \ \ \ \ \ \ statement;
  1218. }
  1219. .Ee
  1220. .Ee
  1221. .LP
  1222. The style above is called ``K\^&\^R style'', and is
  1223. preferred if you haven't already got a favorite.
  1224. With K&R style, the
  1225. .Ep else
  1226. part of an
  1227. \fIif-else\fP statement
  1228. and the
  1229. .Ep while
  1230. part of a \fIdo-while\fP statement
  1231. should appear on the same line as the close brace.
  1232. With most other styles, the braces are always alone on a line.
  1233. .PP
  1234. When a block of code has several labels
  1235. (unless there are a lot of them),
  1236. the labels are placed on separate lines.
  1237. The fall-through feature of the C \fIswitch\fP statement,
  1238. (that is, when there is no
  1239. .Ep break
  1240. between a code segment and the next
  1241. .Ep case
  1242. statement)
  1243. must be commented for future maintenance.
  1244. A lint-style comment/directive is best.
  1245. .Ex
  1246. switch (expr) {
  1247. case ABC:
  1248. case DEF:
  1249.     statement;
  1250.     break;
  1251. case UVW:
  1252.     statement;
  1253.     /*FALLTHROUGH*/
  1254. case XYZ:
  1255.     statement;
  1256.     break;
  1257. }
  1258. .Ee
  1259. .\"
  1260. .\" You won't believe how long I struggled with the format of the
  1261. .\" `switch' statement.  It took a lot of people beating on me to
  1262. .\" convince me that it should look like the if...else arrangement
  1263. .\" that I said is supposed to ``look like a generalized switch''.
  1264. .\" Ok, so I'm a little slow some years...
  1265. .\"
  1266. .PP
  1267. Here, the last
  1268. .Ep break
  1269. is unnecessary, but is required
  1270. because it prevents a fall-through error if another
  1271. .Ep case
  1272. is added later after the last one.
  1273. The
  1274. .Ep default
  1275. case, if used, should be last and does not require a
  1276. .Ep break 
  1277. if it is last.
  1278. .PP
  1279. Whenever an
  1280. .Ec if-else
  1281. statement has a compound statement for either the
  1282. .Ec if
  1283. or
  1284. .Ec else
  1285. section, the statements of both the
  1286. .Ec if
  1287. and
  1288. .Ec else
  1289. sections should both be enclosed in braces
  1290. (called \fIfully bracketed syntax\fP).
  1291. .PP
  1292. .Ex
  1293. if (expr) {
  1294.     statement;
  1295. } else {
  1296.     statement;
  1297.     statement;
  1298. }
  1299. .Ee
  1300. Braces are also essential in \fIif-if-else\fP sequences
  1301. with no second \fIelse\fP such as the following,
  1302. which will be parsed incorrectly if the brace after
  1303. .Ep (ex1)
  1304. and its mate are omitted:
  1305. .Ex
  1306. if (ex1) {
  1307.     if (ex2) {
  1308.         funca();
  1309.     }
  1310. } else {
  1311.     funcb();
  1312. }
  1313. .Ee
  1314. .PP
  1315. An \fIif-else\fP with \fIelse if\fP should
  1316. be written with the \fIelse\fP conditions left-justified.
  1317. .Ex
  1318. if (STREQ (reply, "yes")) {
  1319.     statements for yes
  1320.     ...
  1321. } else if (STREQ (reply, "no")) {
  1322.     ...
  1323. } else if (STREQ (reply, "maybe")) {
  1324.     ...
  1325. } else {
  1326.     statements for default
  1327.     ...
  1328. }
  1329. .Ee
  1330. The format then looks
  1331. like a generalized \fIswitch\fP statement and the
  1332. tabbing reflects the switch between exactly one of several
  1333. alternatives rather than a nesting of statements.
  1334. .PP
  1335. .Ec Do-while
  1336. loops should always have braces around the body. 
  1337. .PP
  1338. The following code is very dangerous:
  1339. .Ex
  1340. #ifdef CIRCUIT
  1341. #    define CLOSE_CIRCUIT(circno)    { close_circ(circno); }
  1342. #else
  1343. #    define CLOSE_CIRCUIT(circno)
  1344. #endif
  1345.  
  1346. \&    ...
  1347.     if (expr)
  1348.         statement;
  1349.     else
  1350.         CLOSE_CIRCUIT(x)
  1351.     ++i;
  1352. .Ee
  1353. Note that on systems where CIRCUIT is not defined
  1354. the statement
  1355. .Ep ++i; '' ``
  1356. will only
  1357. get executed when
  1358. .Ep expr
  1359. is false!
  1360. This example points out both the value
  1361. of naming macros with CAPS and
  1362. of making code fully-bracketed.
  1363. .PP
  1364. Sometimes an
  1365. .Ec if
  1366. causes an unconditional control transfer
  1367. via
  1368. .Ep break ,
  1369. .Ep continue ,
  1370. .Ep goto ,
  1371. or
  1372. .Ep return .
  1373. The
  1374. .Ec else
  1375. should be implicit and the code should not be indented.
  1376. .Ex
  1377. if (level > limit)
  1378.     return (OVERFLOW)
  1379. normal();
  1380. return (level);
  1381. .Ee
  1382. The ``flattened'' indentation tells the reader that the boolean test
  1383. is invariant over the rest of the enclosing block.
  1384. .NH
  1385. Operators
  1386. .PP
  1387. Unary operators should not be separated from their single operand.
  1388. Generally, all binary operators
  1389. except
  1390. .Ep "\&." ' `
  1391. and
  1392. Ep "\->" ' `
  1393. should be separated from their operands by blanks.
  1394. Some judgement is called for in the case of complex expressions,
  1395. which may be clearer if the ``inner'' operators are not surrounded
  1396. by spaces and the ``outer'' ones are.
  1397. .PP
  1398. If you think an expression will be hard to read,
  1399. consider breaking it across lines.
  1400. Splitting at the lowest-precedence operator near the break is best.
  1401. Since C has some unexpected precedence rules,
  1402. expressions involving mixed operators should be parenthesized.
  1403. Too many parentheses, however,
  1404. can make a line \fIharder\fP to read
  1405. because humans aren't good at parenthesis-matching.
  1406. .PP
  1407. There is a time and place for the binary comma operator,
  1408. but generally it should be avoided.
  1409. The comma operator is most useful
  1410. to provide multiple initializations or operations,
  1411. as in \fIfor\fP statements.
  1412. Complex expressions,
  1413. for instance those with nested ternary
  1414. .Ec ?\^:
  1415. operators,
  1416. can be confusing and should be avoided if possible.
  1417. There are some macros like
  1418. .Ep getchar
  1419. where both the ternary
  1420. operator and comma operators are useful.
  1421. The logical expression operand before the
  1422. .Ec ?\^:
  1423. should be parenthesized and both return values must be the same type.
  1424. .NH
  1425. Naming Conventions
  1426. .PP
  1427. Individual projects will no doubt have their own naming conventions.
  1428. There are some general rules however.
  1429. .IP \0\0\(bu
  1430. Names with leading and trailing underscores are reserved for system
  1431. purposes and should not be used for any user-created names.
  1432. Most systems use them for names
  1433. that the user should not have to know.
  1434. If you must have your own private identifiers,
  1435. begin them with a letter or two identifying the
  1436. package to which they belong.
  1437. .IP \0\0\(bu
  1438. #define constants should be in all CAPS.
  1439. .IP \0\0\(bu
  1440. Enum constants are Capitalized or in all CAPS
  1441. .IP \0\0\(bu
  1442. Function, typedef, and variable names, as well as struct, union, and
  1443. enum tag names should be in lower case.
  1444. .IP \0\0\(bu
  1445. Many macro ``functions'' are in all CAPS.
  1446. Some macros (such as
  1447. .Ep getchar
  1448. and
  1449. .Ep putchar )
  1450. are in lower case
  1451. since they may also exist as functions.
  1452. Lower-case macro names are only acceptable if the macros behave
  1453. like a function call,
  1454. that is, they evaluate their parameters \fIexactly\fP once and
  1455. do not assign values to named parameters.
  1456. Sometimes it is impossible to write a macro that behaves like a
  1457. function even though the arguments are evaluated exactly once.
  1458. .IP \0\0\(bu
  1459. Avoid names that differ only in case, like \fIfoo\fP and \fIFoo\fP.
  1460. Similarly, avoid \fIfoobar\fP and \fIfoo_bar\fP.
  1461. The potential for confusion is considerable.
  1462. .IP \0\0\(bu
  1463. Similarly, avoid names that look like each other.
  1464. On many terminals and printers, `l', `1' and `I' look quite similar.
  1465. A variable named `l' is particularly bad because it looks so much like
  1466. the constant `1'.
  1467. .PP
  1468. In general, global names (including
  1469. .Ec enum s)
  1470. should have a
  1471. common prefix identifying the module that they belong with.
  1472. Globals may alternatively be grouped in a global structure.
  1473. Typedeffed names often have
  1474. .Ep _t '' ``
  1475. appended to their name.
  1476. .PP
  1477. Avoid names that might conflict with various standard
  1478. library names.
  1479. Some systems will include more library code than you want.
  1480. Also, your program may be extended someday.
  1481. .NH
  1482. Constants
  1483. .PP
  1484. Numerical constants should not be coded directly.
  1485. The
  1486. .Ec #define
  1487. feature of the C preprocessor should be used to
  1488. give constants meaningful names.
  1489. Symbolic constants make the code easier to read.
  1490. Defining the value in one place
  1491. also makes it easier to administer large programs since the
  1492. constant value can be changed uniformly by changing only the
  1493. define.
  1494. The enumeration data type is a better way to declare variables
  1495. that take on only a discrete set of values, since
  1496. additional type checking is often available.
  1497. At the very least, any directly-coded numerical constant must have a
  1498. comment explaining the derivation of the value.
  1499. .PP
  1500. Constants should be defined consistently with their use;
  1501. e.g. use
  1502. .Ep 540.0
  1503. for a float instead of
  1504. .Ep 540
  1505. with an implicit float cast.
  1506. There are some cases where the constants 0 and 1 may appear as
  1507. themselves instead of as defines.
  1508. For example if a
  1509. .Ec for
  1510. loop indexes through an array, then
  1511. .Ex
  1512. for (i = 0; i < ARYBOUND; i++)
  1513. .Ee
  1514. is reasonable while the code
  1515. .Ex
  1516. door_t *front_door = opens(door[i], 7);
  1517. if (front_door =\^= 0)
  1518.     error("can't open %s\\\\n", door[i]);
  1519. .Ee
  1520. is not.
  1521. In the last example
  1522. .Ep front_door
  1523. is a pointer.
  1524. When a value is a pointer it should be compared to
  1525. .Ep NULL
  1526. instead of 0.
  1527. .Ec NULL
  1528. is available
  1529. either as part of the standard I/O library's header file \fIstdio.h\fP
  1530. or in \fIstdlib.h\fP for newer systems.
  1531. Even simple values like 1 or 0 are often better expressed using
  1532. defines like
  1533. .Ec TRUE
  1534. and
  1535. .Ec FALSE
  1536. (sometimes
  1537. .Ec YES
  1538. and
  1539. .Ec NO
  1540. read better).
  1541. .PP
  1542. Simple character constants should be defined as character literals
  1543. rather than numbers.
  1544. Non-text characters are discouraged as non-portable.
  1545. If non-text characters are necessary,
  1546. particularly if they are used in strings,
  1547. they should be written using a escape character of three octal digits
  1548. rather than one
  1549. (e.g.,
  1550. .Ep \&'\&\e007' ).
  1551. Even so, such usage should be considered machine-dependent and treated
  1552. as such.
  1553. .NH
  1554. Macros
  1555. .PP
  1556. Complex expressions can be used as macro parameters,
  1557. and operator-precedence problems can arise unless all occurrences of
  1558. parameters have parentheses around them.
  1559. There is little that can be done about the problems caused by side
  1560. effects in parameters
  1561. except to avoid side effects in expressions (a good idea anyway)
  1562. and, when possible,
  1563. to write macros that evaluate their parameters exactly once.
  1564. There are times when it is impossible to write macros that act exactly
  1565. like functions.
  1566. .\" .PP
  1567. .\" Here are some classic macros.
  1568. .\" .DS
  1569. .\" #define INV(val)    1/val
  1570. .\" \&...
  1571. .\"     y = INV(*x);        /* turns into ``start comment''! */
  1572. .\" .DE
  1573. .\" (The above does \fInot\fP start a comment with ANSI preprocesors.)
  1574. .\" .DS
  1575. .\" #define MAX(a,b)    (((a)>(b)) ? (a) : (b) )
  1576. .\" \&...
  1577. .\"     k = MAX(i++,j++);
  1578. .\" .DE
  1579. .PP
  1580. Some macros also exist as functions (e.g.,
  1581. .Ep getc
  1582. and
  1583. .Ep fgetc ).
  1584. The macro should be used in implementing the function
  1585. so that changes to the macro
  1586. will be automatically reflected in the function.
  1587. Care is needed when interchanging macros and functions since function
  1588. parameters are passed by value, while macro parameters are passed by
  1589. name substitution.
  1590. .\" Carefree use of macros requires care when they are defined.
  1591. Carefree use of macros requires that they be declared carefully.
  1592. .PP
  1593. Macros should avoid using globals, since the global name may be
  1594. hidden by a local declaration.
  1595. Macros that change named parameters (rather than the storage they
  1596. point at) or may be used as the left-hand side of an assignment
  1597. should mention this in their comments.
  1598. Macros that take no parameters but reference variables,
  1599. are long,
  1600. or are aliases for function calls
  1601. should be given an empty parameter list, e.g.,
  1602. .Ex
  1603. #define    OFF_A(\^\^)    (a_global+OFFSET)
  1604. #define    BORK(\^\^)    (zork(\^))
  1605. #define    SP3(\^\^)    if (b) { int x; av = f (&x); bv += x; }
  1606. .Ee
  1607. .PP
  1608. Macros save function call/return overhead,
  1609. but when a macro gets long, the effect of the call/return
  1610. becomes negligible, so a function should be used instead.
  1611. .PP
  1612. In some cases it is appropriate to make the compiler
  1613. insure that a macro is terminated with a semicolon.
  1614. .Ex
  1615. if (x==3)
  1616.     SP3(\^\^);
  1617. else
  1618.     BORK(\^\^);
  1619. .Ee
  1620. If the semicolon is omitted after the call to
  1621. .Ep SP3 ,
  1622. then the
  1623. .Ep else
  1624. will (silently!) become associated with the
  1625. .Ep if
  1626. in the
  1627. .Ep SP3
  1628. macro.
  1629. With the semicolon, the
  1630. .Ep else
  1631. doesn't match \fBany\fP
  1632. .Ep if !
  1633. The macro
  1634. .Ep SP3
  1635. can be written safely as
  1636. .Ex
  1637. #define SP3(\^\^) \\\\
  1638.     do { if (b) { int x; av = f (&x); bv += x; }} while (0)
  1639. .Ee
  1640. Writing out the enclosing
  1641. .Ec do-while
  1642. by hand is awkward and some compilers and tools
  1643. may complain that there is a constant in the
  1644. .Ep while '' ``
  1645. conditional.
  1646. A macro for declaring statements may make programming easier.
  1647. .Ex
  1648. #ifdef lint
  1649.     static int ZERO;
  1650. #else
  1651. #    define ZERO 0
  1652. #endif
  1653. #define STMT( stuff )        do { stuff } while (ZERO)
  1654. .Ee
  1655. Declare
  1656. .Ep SP3
  1657. with
  1658. .Ex
  1659. #define SP3(\^\^) \\\\
  1660.     STMT( if (b) { int x; av = f (&x); bv += x; } )
  1661. .Ee
  1662. Using
  1663. .Ep STMT
  1664. will help prevent small typos from silently changing programs.
  1665. .PP
  1666. Except for type casts,
  1667. .Ep sizeof ,
  1668. and hacks such as the above,
  1669. macros should contain keywords only if the entire
  1670. macro is surrounded by braces.
  1671. .NH
  1672. Conditional Compilation.
  1673. .PP
  1674. Conditional compilation is useful for things like
  1675. machine-dependencies,
  1676. debugging,
  1677. and for setting certain options at compile-time.
  1678. Beware of conditional compilation.
  1679. Various controls can easily combine in unforeseen ways.
  1680. If you #ifdef machine dependencies,
  1681. make sure that when no machine is specified,
  1682. the result is an error, not a default machine.
  1683. (Use
  1684. .Ep #error '' ``
  1685. and indent it so it works with older compilers.)
  1686. If you #ifdef optimizations,
  1687. the default should be the unoptimized code
  1688. rather than an uncompilable program.
  1689. Be sure to test the unoptimized code.
  1690. .PP
  1691. Note that the text inside of an #ifdeffed section may be scanned
  1692. (processed) by the compiler, even if the #ifdef is false.
  1693. Thus, even if the #ifdeffed part of the file never gets compiled
  1694. (e.g.,
  1695. .Ep "#ifdef COMMENT" ),
  1696. it cannot be arbitrary text.
  1697. .PP
  1698. Put #ifdefs in header files instead of source files when possible.
  1699. Use the #ifdefs to define macros
  1700. that can be used uniformly in the code.
  1701. For instance, a header file for checking memory allocation
  1702. might look like (omitting definitions for
  1703. .Ep REALLOC
  1704. and
  1705. .Ep FREE ):
  1706. .Ex
  1707. #ifdef DEBUG
  1708.     extern void *mm_malloc();
  1709. #    define MALLOC(size) (mm_malloc(size))
  1710. #else
  1711.     extern void *malloc();
  1712. #    define MALLOC(size) (malloc(size))
  1713. #endif
  1714. .Ee
  1715. .PP
  1716. Conditional compilation should generally be
  1717. on a feature-by-feature basis.
  1718. Machine or operating system dependencies
  1719. should be avoided in most cases.
  1720. .Ex
  1721. #ifdef BSD4
  1722.     long t = time ((long *)NULL);
  1723. #endif
  1724. .Ee
  1725. The preceding code is poor for two reasons:
  1726. there may be 4BSD systems for which there is a better choice,
  1727. and there may be non-4BSD systems for which the above \fIis\fP the
  1728. best code.
  1729. Instead, use \fIdefine\fP symbols
  1730. such as
  1731. .Ep TIME_LONG
  1732. and
  1733. .Ep TIME_STRUCT
  1734. and define the appropriate one
  1735. in a configuration file such as \fIconfig.h\fP.
  1736. .NH
  1737. Debugging
  1738. .QP
  1739. .ce
  1740. ``\fIC Code.  C code run.  Run, code, run...  PLEASE!!!\fP'' \(em Barbara Tongue
  1741. .\"
  1742. .\" Recently: "C Code.  C Code Run.  Run, Code, RUN!  PLEASE!!!"
  1743. .\" But I think the original is accurate.
  1744. .\"
  1745. .PP
  1746. If you use
  1747. .Ec enum s,
  1748. the first enum constant should have a non-zero value,
  1749. or the first constant should indicate an error.
  1750. .Ex
  1751. enum { STATE_ERR, STATE_START, STATE_NORMAL, STATE_END } state_t;
  1752. enum { VAL_NEW=1, VAL_NORMAL, VAL_DYING, VAL_DEAD } value_t;
  1753. .Ee
  1754. Uninitialized values will then often ``catch themselves''.
  1755. .PP
  1756. Check for error return values, even from functions that ``can't''
  1757. fail.
  1758. Consider that
  1759. .Ep close(\^)
  1760. and
  1761. .Ep fclose(\^)
  1762. can and do fail, even when all prior file operations have succeeded.
  1763. Write your own functions so that they test for errors
  1764. and return error values or abort the program in a well-defined way.
  1765. Include a lot of debugging and error-checking code
  1766. and leave most of it in the finished product.
  1767. Check even for ``impossible'' errors. [8]
  1768. .PP
  1769. Use the
  1770. .Ec assert
  1771. facility to insist that
  1772. each function is being passed well-defined values,
  1773. and that intermediate results are well-formed.
  1774. .PP
  1775. Build in the debug code using as few #ifdefs as possible.
  1776. For instance, if
  1777. .Ep mm_malloc '' ``
  1778. is a debugging memory allocator, then
  1779. .Ep MALLOC
  1780. will select the appropriate allocator,
  1781. avoids littering the code with #ifdefs,
  1782. and makes clear the difference between allocation calls being debugged
  1783. and extra memory that is allocated only during debugging.
  1784. .Ex
  1785. #ifdef DEBUG
  1786. #    define MALLOC(size)  (mm_malloc(size))
  1787. #else
  1788. #    define MALLOC(size)  (malloc(size))
  1789. #endif
  1790. .Ee
  1791. .PP
  1792. Check bounds even on things that ``can't'' overflow.
  1793. A function that writes on to variable-sized storage
  1794. should take an argument
  1795. .Ep maxsize
  1796. that is the size of the destination.
  1797. If there are times when the size of the destination is unknown,
  1798. some `magic' value of
  1799. .Ep maxsize
  1800. should mean ``no bounds checks''.
  1801. When bound checks fail,
  1802. make sure that the function does something useful
  1803. such as abort or return an error status.
  1804. .Ex
  1805. /*
  1806.  * INPUT: A null-terminated source string `src' to copy from and
  1807.  * a `dest' string to copy to.  `maxsize' is the size of `dest'
  1808.  * or UINT_MAX if the size is not known.  `src' and `dest' must
  1809.  * both be shorter than UINT_MAX, and `src' must be no longer than
  1810.  * `dest'.
  1811.  * OUTPUT: The address of `dest' or NULL if the copy fails.
  1812.  * `dest' is modified even when the copy fails.
  1813.  */
  1814.     char *
  1815. copy (dest, maxsize, src)
  1816.     char *dest, *src;
  1817.     unsigned maxsize;
  1818. .\"
  1819. .\" That should be `size_t', rather than `unsigned'?
  1820. .\"
  1821. {
  1822.     char *dp = dest;
  1823.  
  1824.     while (maxsize\-\^\- > 0)
  1825.         if ((*dp++ = *src++) =\^= '\\\\0')
  1826.             return (dest);
  1827.  
  1828.     return (NULL);
  1829. }
  1830. .Ee
  1831. .PP
  1832. In all, remember that
  1833. a program that produces wrong answers twice as fast is infinitely
  1834. slower.
  1835. The same is true of programs that crash occasionally
  1836. or clobber valid data.
  1837. .NH
  1838. Portability
  1839. .QP
  1840. .ad r
  1841. ``\fIC combines the power of assembler with
  1842. the portability of assembler.\fP''
  1843. .br
  1844. \(em Anonymous, alluding to Bill Thacker.
  1845. .br
  1846. .ad b
  1847. .LP
  1848. .\"
  1849. .\" .QP
  1850. .\" .ad r
  1851. .\" ``\fI"C" combines the power of assembly language with
  1852. .\" the flexibility of assembly language.\fP''
  1853. .\" .br
  1854. .\" \(em Bill Thacker
  1855. .\" .ad b
  1856. .\"
  1857. .PP
  1858. The advantages of portable code are well known.
  1859. This section gives some guidelines for writing portable code.
  1860. Here, ``portable'' means that a source file
  1861. can be compiled and executed on different machines
  1862. with the only change being the inclusion of possibly
  1863. different header files and the use of different compiler flags.
  1864. The header files will contain #defines and typedefs that may vary from
  1865. machine to machine.
  1866. In general, a new ``machine'' is different hardware,
  1867. a different operating system, a different compiler,
  1868. or any combination of these.
  1869. Reference [1] contains useful information on both style and portability.
  1870. .\" Does it really?
  1871. The following is a list of pitfalls to be avoided and recommendations
  1872. to be considered when designing portable code:
  1873. .IP \0\0\(bu
  1874. Write portable code first,
  1875. worry about detail optimizations only on machines where they
  1876. prove necessary.
  1877. Optimized code is often obscure.
  1878. Optimizations for one machine may produce worse code on another.
  1879. Document performance hacks and localize them as much as possible.
  1880. Documentation should explain \fIhow\fP it works and \fIwhy\fP
  1881. it was needed (e.g., ``loop executes 6 zillion times'').
  1882. .IP \0\0\(bu
  1883. Recognize that some things are inherently non-portable.
  1884. Examples are code to deal with particular hardware registers such as
  1885. the program status word,
  1886. and code that is designed to support a particular piece of hardware,
  1887. such as an assembler or I/O driver.
  1888. Even in these cases there are many routines and data organizations
  1889. that can be made machine independent.
  1890. .IP \0\0\(bu
  1891. Organize source files so that the machine-independent
  1892. code and the machine-dependent code are in separate files.
  1893. Then if the program is to be moved to a new machine,
  1894. it is a much easier task to determine what needs to be changed.
  1895. Comment the machine dependence in the headers of the appropriate
  1896. files.
  1897. .IP \0\0\(bu
  1898. Any behavior that is described as ``implementation defined''
  1899. should be treated as a machine (compiler) dependency.
  1900. Assume that the compiler or hardware does it some completely screwy
  1901. way.
  1902. .IP \0\0\(bu
  1903. Pay attention to word sizes.
  1904. Objects may be non-intuitive sizes,
  1905. Pointers are not always the same size as \fIint\fPs,
  1906. the same size as each other,
  1907. or freely interconvertible.
  1908. The following table shows bit sizes for basic types in C for various
  1909. machines and compilers.
  1910. .br
  1911. .ne 2i
  1912. .TS
  1913. center;
  1914. l c c c c c c c
  1915. l c c c c c c c
  1916. l r r r r r r r.
  1917. type    pdp11    VAX/11    68000    Cray-2    Unisys    Harris    80386
  1918.     series        family        1100    H800    
  1919. _
  1920. char    8    8    8    8    9    8    8
  1921. short    16    16    8/16    64(32)    18    24    8/16
  1922. int    16    32    16/32    64(32)    36    24    16/32
  1923. long    32    32    32    64    36    48    32
  1924. char*    16    32    32    64    72    24    16/32/48
  1925. int*    16    32    32    64(24)    72    24    16/32/48
  1926. int(*)(\^\^)    16    32    32    64    576    24    16/32/48
  1927. .TE
  1928. .\" 
  1929. .\" blarson%skat.usc.edu@oberon.usc.edu (Bob Larson) sez for a pr1me
  1930. .\" int=16 is a compile-time option.  pointer size depends on which
  1931. .\" instruction set you generate code for, only 32 bits are significant
  1932. .\" on non-char* pointers (extra 16 bits allocated but not used.)
  1933. .\" 
  1934. .\" beaver.cs.washington.edu!cornell!calvin!johns (John Sahr) sez
  1935. .\" the Harris H800/H100 series has 3-byte words.  Float and double
  1936. .\" are the same bit-size but are different precision; two bytes are
  1937. .\" thrown away for floats.  Int* and char* are same size but 2 bits
  1938. .\" are reserved for the byte pointer within a word.  H1000/H12000
  1939. .\" have software triple and quad precision for FORTRAN, 9 & 12 bytes.
  1940. .\"
  1941. .\" Theodore Stevens Norvell <norvell@csri.toronto.edu> on the Control
  1942. .\" Data Cyber-180 (aka Cyber 900).  Pointers hold only 48 bits of
  1943. .\" useful data (44 for virtual byte address, 4 for security) but are
  1944. .\" padded to make them more interchangeable with ints.
  1945. .\" 
  1946. .\" DEEBE@SCIENCE.UTAH.EDU (Nelson H.F. Beebe) on 36-bit DEC-20:
  1947. .\" 4 compilers, including PCC-20 (Johnson's PCC ported to TOPS-20 by
  1948. .\" Lereau@cs.utah.edu), KCC-20 (Kok Chen at Stanford, Ken Harrenstien
  1949. .\" and Ian Macky at SRI), New Mexico Tech C, Sargasso C compiler
  1950. .\" (from BBN, he thinks).  Most still using DEC-20's use KCC.
  1951. .\" [*] Note that KCC-20 has 4 pointer formats based on local/global
  1952. .\" and char*/non-char* usage.  The following fails:
  1953. .\"     int *p = malloc( sizeof(int) );
  1954. .\"    free( p );
  1955. .\" It works correctly with casts to int* from malloc and to char* for
  1956. .\" free.
  1957. .\" 
  1958. .\" type    pr1me    H800    Cyber    PCC-20    KCC-20
  1959. .\"                900
  1960. .\"
  1961. .\" char    8    8    8    36    9
  1962. .\" short    16    24    32    36    18
  1963. .\" int        16/32    24    64    36    36
  1964. .\" long    32    48    64    36    36
  1965. .\" char*    32(48)    24    64    36    36[*]
  1966. .\" int*    32(48)    ?    64    36    36[*]
  1967. .\" int(*)()    32(48)    24    64    36    36[*]
  1968. .\" float    ?    48    64    36    36
  1969. .\" double    ?    48    64    36    72
  1970. .\" long double    ?    ?    128    <none>    <none>
  1971. .\" 
  1972. Some machines have more than one possible size for a given type.
  1973. The size you get can depend both on the compiler
  1974. and on various compile-time flags.
  1975. The following table shows ``safe'' type sizes on the majority of
  1976. systems.
  1977. Unsigned numbers are the same bit size as signed numbers.
  1978. .KS
  1979. .TS
  1980. center;
  1981. c c c
  1982. l r c.
  1983. Type    Minimum    No Smaller
  1984.     # Bits    Than
  1985. _
  1986. char    8
  1987. short    16    char
  1988. int    16    short
  1989. long    32    int
  1990. float    24
  1991. double    38    float
  1992. any *    14
  1993. char *    15    any *
  1994. void *    15    any *
  1995. .TE
  1996. .KE
  1997. .IP \0\0\(bu
  1998. The
  1999. .Ec void*
  2000. type
  2001. is guaranteed to have enough bits
  2002. of precision to hold a pointer to any data object.
  2003. The
  2004. .Ec void(*)(\^\^)
  2005. type is guaranteed to be able to hold a pointer to any function.
  2006. Use these types when you need a generic pointer.
  2007. (Use
  2008. .Ec char*
  2009. and
  2010. .Ec char(*)(\^\^) ,
  2011. respectively, in older compilers).
  2012. .\"
  2013. .\" Any return value should do; `int(*)()' makes more sense,
  2014. .\" but then it's hard to #define back and forth between dpANS
  2015. .\" (void means void) and older compilers (#define void ...).
  2016. .\" You still bite the farm if the compiler understands void but
  2017. .\" not void*.
  2018. .\"
  2019. Be sure to cast pointers back to the correct type before using them.
  2020. .IP \0\0\(bu
  2021. Even when, say, an
  2022. .Ec int*
  2023. and a
  2024. .Ec char*
  2025. are the same \fIsize\fP, they may have different \fIformats\fP.
  2026. For example, the following will fail on some machines that have
  2027. .Ep sizeof(int*)
  2028. equal to
  2029. .Ep sizeof(char*) .
  2030. The code fails because
  2031. .Ep free
  2032. expects a
  2033. .Ec char*
  2034. and gets passed an
  2035. .Ec int* .
  2036. .\" See the comment above about the KCC compiler for DEC-20s
  2037. .Ex
  2038. int *p = (int *) malloc (sizeof(int));
  2039. free (p);
  2040. .Ee
  2041. .\"
  2042. .\" Another example:
  2043. .\" Consider the \fBqsort\fP routine, which takes a pointer to an array
  2044. .\" of `things', the size of each element, and a comparison function.
  2045. .\" Sorting an array of \fBstruct foo\fP, you may be tempted to say
  2046. .\" .Ex
  2047. .\" int compare (struct foo *a, struct foo *b) { ... }
  2048. .\" qsort ((void*)argv, argc, sizeof(struct foo), compare);
  2049. .\" .Ee
  2050. .\" This will surely bomb on some machines, however.
  2051. .\" .Ep compare(\^)
  2052. .\" takes pointers to two
  2053. .\" .Ec struct Ps,
  2054. .\" while
  2055. .\" .Ep qsort(\^)
  2056. .\" will \fIcall\fP it with two
  2057. .\" .Ec void* s.
  2058. .\"
  2059. .IP \0\0\(bu
  2060. Note that
  2061. the \fIsize\fP of an object does not guarantee the \fIprecision\fP of
  2062. that object.
  2063. The Cray-2 may use 64 bits to store an
  2064. .Ec int ,
  2065. but a \fIlong\fP cast into an
  2066. .Ec int
  2067. and back to a
  2068. .Ec long
  2069. may be truncated to 32 bits.
  2070. .IP \0\0\(bu
  2071. The integer
  2072. .Ec constant
  2073. zero may be cast to any pointer type.
  2074. The resulting pointer is called a
  2075. \fInull pointer\fP
  2076. for that type, and is different from any other pointer of that type.
  2077. A null pointer always compares equal to the constant zero.
  2078. A null pointer might \fInot\fP compare equal with a variable
  2079. that has the value zero.
  2080. Null pointers are \fInot\fP always stored with all bits zero.
  2081. Null pointers for two different types are sometimes different.
  2082. A null pointer of one type cast in to a pointer of another
  2083. type will be cast in to the null pointer for that second type.
  2084. .\"
  2085. .\" The name of the null pointer is called "NULL".
  2086. .\" But that's just what the name is called.
  2087. .\" The name is really "0" (cast or otherwise coerced to a pointer value).
  2088. .\" But again, that's just the name.
  2089. .\" The actual null pointer can have any bitwise value the implementor chooses.
  2090. .\"            -- Wayne Throop (alluding to Lewis Carroll)
  2091. .\"
  2092. .\" In C, the name of the nil pointer is called "NULL".
  2093. .\" But that's only what the name is CALLED, you see.
  2094. .\" The NAME of the nil pointer is "0".
  2095. .\" The nil pointer itself can have any bit pattern it pleases. 
  2096. .\"            -- Wayne Throop (alluding to Lewis Carroll)
  2097. .\"
  2098. .IP \0\0\(bu
  2099. On \s-1ANSI\s+1 compilers, when two pointers of the same type access
  2100. the same storage, they will compare as equal.
  2101. When non-zero integer constants are cast to pointer types,
  2102. they may become identical to other pointers.
  2103. On non-\s-1ANSI\s+1 compilers, pointers that
  2104. access the same storage may compare as different.
  2105. The following two pointers, for instance,
  2106. may or may not compare equal,
  2107. and they may or may not access the same storage\*f.
  2108. .FS
  2109. .IP \*F
  2110. The code may also fail to compile, fault on pointer creation,
  2111. fault on pointer comparison, or fault on pointer dereferences.
  2112. .FE
  2113. .Ex
  2114. ((int *) 2 )
  2115. ((int *) 3 )
  2116. .Ee
  2117. .\"
  2118. .\" This is true, for instance, on the 8086, where the least-
  2119. .\" -significant bit is always ignored, except when accessing
  2120. .\" byte-sized values.  The pointer comparison (==) uses \fIall\fP
  2121. .\" bits, so the two pointers do \fInot\fP compare the same.
  2122. .\"
  2123. If you need `magic' pointers other than NULL,
  2124. either allocate some storage or treat the pointer as
  2125. a machine dependence.
  2126. .Ex
  2127. extern int x_int_dummy;        /* in x.c */
  2128. #define X_FAIL    (NULL)
  2129. #define X_BUSY    (&x_int_dummy)
  2130. .Ee
  2131. .Ex
  2132. #define X_FAIL    (NULL)
  2133. #define X_BUSY    MD_PTR1        /* MD_PTR1 from "machdep.h" */
  2134. .Ee
  2135. .IP \0\0\(bu
  2136. Floating-point numbers have both a \fIprecision\fP and a \fIrange\fP.
  2137. These are independent of the size of the object.
  2138. Thus, overflow (underflow) for a 32-bit floating-point number will
  2139. happen at different values on different machines.
  2140. Also,
  2141. 4.9
  2142. times
  2143. 5.1
  2144. will yield
  2145. two different numbers on two different machines.
  2146. Differences in rounding and truncation can give surprisingly
  2147. different answers.
  2148. .\"
  2149. .\" .QP
  2150. .\" ``\fI10.0 times 0.1 is hardly ever 1.0\fP'' -- Kernighan and Plauger [9]
  2151. .\"
  2152. .IP \0\0\(bu
  2153. On some machines,
  2154. a
  2155. .Ec double
  2156. may have \fIless\fP range or precision than a
  2157. .Ec float .
  2158. .IP \0\0\(bu
  2159. On some machines the first half of a
  2160. .Ec double
  2161. may be a
  2162. .Ec float
  2163. with similar value.
  2164. Do \fInot\fP depend on this.
  2165. .IP \0\0\(bu
  2166. Watch out for signed characters.
  2167. On some \s-1VAX\s+1es, for instance,
  2168. characters are sign extended when used in expressions,
  2169. which is not the case on many other machines.
  2170. Code that assumes signed/unsigned is unportable.
  2171. For example,
  2172. .Ep array[c]
  2173. won't work if
  2174. .Ep c
  2175. is supposed to be positive and is instead signed and negative.
  2176. If you must assume signed or unsigned characters, comment them as
  2177. .Ep SIGNED
  2178. or
  2179. .Ep UNSIGNED .
  2180. Unsigned behavior can be guaranteed with
  2181. .Ep "unsigned char" .
  2182. .IP \0\0\(bu
  2183. Avoid assuming \s-1ASCII\s+1.
  2184. .\"
  2185. .\" (Use
  2186. .\" .Ep "<ctype.h>"
  2187. .\" where possible, but beware that their behavior varies considerably
  2188. .\" between C implementations.
  2189. .\" For instance, if c is not an upper-case letter,
  2190. .\" tolower(c) may return c or garbage.)
  2191. .\"
  2192. If you must assume, document and localize.
  2193. Remember that characters may hold (much) more than 8 bits.
  2194. .IP \0\0\(bu
  2195. Code that takes advantage of the two's complement representation of
  2196. numbers on most machines should not be used.
  2197. Optimizations that replace arithmetic operations with equivalent
  2198. shifting operations are particularly suspect.
  2199. If absolutely necessary, machine-dependent code should be #ifdeffed
  2200. or operations should be performed by #ifdeffed macros.
  2201. You should weigh the time savings with the potential for obscure
  2202. and difficult bugs when your code is moved.
  2203. .IP \0\0\(bu
  2204. In general, if the word size or value range is important,
  2205. typedef ``sized'' types.
  2206. Large programs should have a central header file which supplies
  2207. typedefs for commonly-used width-sensitive types, to make
  2208. it easier to change them and to aid in finding width-sensitive code.
  2209. Unsigned types other than
  2210. .Ec "unsigned int"
  2211. are highly compiler-dependent.
  2212. If a simple loop counter is being used where either 16 or 32 bits will
  2213. do, then use
  2214. .Ec int ,
  2215. since it will get the most efficient (natural)
  2216. unit for the current machine.
  2217. .\"
  2218. .\" <side comment>
  2219. .\" Actually, there are many machines that use ``unnatural''
  2220. .\" int sizes to cope with ``the world is a \s-1VAX\s+1'' problems.
  2221. .\" The rule int == natural is still true, though.
  2222. .\" Modern compilers have a switch that lets you select either
  2223. .\" efficiency or bogus-\s-1VAX\s+1-code-compatibility.
  2224. .\" On the other hand, this is still a lie, because the libraries
  2225. .\" must work in any event.
  2226. .\" On the other (third?) hand, modern systems are being fixed.
  2227. .\"
  2228. .IP \0\0\(bu
  2229. Data \fIalignment\fP is also important.
  2230. For instance,
  2231. on various machines a 4-byte integer may start at any address,
  2232. start only at an even address, or start only at a multiple-of-four
  2233. address.
  2234. Thus, a particular structure may have its elements
  2235. at different offsets on different machines,
  2236. even when given elements are the same size on all machines.
  2237. Indeed, a structure of a 32-bit pointer and an 8-bit character may be
  2238. 3 sizes on 3 different machines.
  2239. As a corollary, pointers to objects may not be interchanged freely;
  2240. saving an integer through a pointer
  2241. to 4 bytes starting at an odd address
  2242. will sometimes work,
  2243. sometimes cause a core dump,
  2244. and sometimes fail silently (clobbering other data in the process).
  2245. .\"
  2246. .\" In particular, the \s-1VAX\s+1 will work, the 68000 (tho' not necessarily
  2247. .\" other family members) will dump, and the 8086 (tho' not
  2248. .\" necessarily other members) will ignore the lowest bit.
  2249. .\" The IBM RT will silently round the address down to the nearest
  2250. .\" multiple of four.
  2251. .\"
  2252. Pointer-to-character is a particular trouble spot on machines which
  2253. do not address to the byte.
  2254. Alignment considerations and loader peculiarities make it very rash
  2255. to assume that two consecutively-declared variables are together
  2256. in memory, or that a variable of one type is aligned appropriately
  2257. to be used as another type.
  2258. .IP \0\0\(bu
  2259. The bytes of a word are of increasing significance with increasing
  2260. address on machines such as the \s-1VAX\s+1 (little-endian)
  2261. and of decreasing significance with increasing address on other
  2262. machines such as the 68000 (big-endian).
  2263. The order of bytes in a word and of words in larger
  2264. objects (say, a double word) might not be the same.
  2265. .\"
  2266. .\" Consider, for example, the PDP-11, in which words are
  2267. .\" little-endian, but the most-significant word of a long is stored
  2268. .\" first.
  2269. .\"
  2270. Hence any code that depends on the left-right orientation of bits
  2271. in an object deserves special scrutiny.
  2272. Bit fields within structure members will only be portable so long as
  2273. two separate fields are never concatenated and treated as a unit. [1,3]
  2274. Actually, it is nonportable to concatenate \fIany\fP two variables.
  2275. .IP \0\0\(bu
  2276. There may be unused holes in structures.
  2277. Suspect unions used for type cheating.
  2278. Specifically, a value should not be stored as one type and retrieved as
  2279. another.
  2280. An explicit tag field for unions may be useful.
  2281. .\"
  2282. .\" .Ex
  2283. .\" enum union_tag_t { UT_ERROR, UT_INT, UT_FLOAT };
  2284. .\" struct good_t {
  2285. .\"     enum union_tag_t tag;
  2286. .\"     union {
  2287. .\"         int i;
  2288. .\"         float f;
  2289. .\"         } u;
  2290. .\" } good_t;
  2291. .\" .Ee
  2292. .\"
  2293. .IP \0\0\(bu
  2294. Different compilers use different conventions for returning
  2295. structures.
  2296. This causes a problem when libraries return structure values
  2297. to code compiled with a different compiler.
  2298. Structure pointers are not a problem.
  2299. .\"
  2300. .\" Potentially, \fIany\fP parameter passing mechanism will vary
  2301. .\" between compilers.
  2302. .\" In general, compilers return word-size units in a fixed register
  2303. .\" and (in general) structure pointers are word-sized, so structure
  2304. .\" pointers are not a problem.
  2305. .\"
  2306. .IP \0\0\(bu
  2307. Do not make assumptions about the parameter passing mechanism.
  2308. especially pointer sizes and parameter evaluation order, size, etc.
  2309. The following code, for instance, is \fIvery\fP nonportable.
  2310. .Ex
  2311.     c = foo (getchar(), getchar());
  2312.  
  2313.     char
  2314. foo (c1, c2, c3)
  2315.     char c1, c2, c3;
  2316. {
  2317.     char bar = *(&c1 + 1);
  2318.     return (bar);            /* often won't return c2 */
  2319. }
  2320. .\"
  2321. .\" It can be argued that if this *does* return c2, then
  2322. .\" sizeof(char) == sizeof(int).
  2323. .\"
  2324. .Ee
  2325. This example has lots of problems.
  2326. The stack may grow up or down
  2327. (indeed, there need not even be a stack!).
  2328. Parameters may be widened when they are passed,
  2329. so a
  2330. .Ec char
  2331. might be passed as an
  2332. .Ec int ,
  2333. for instance.
  2334. Arguments may be pushed left-to-right, right-to-left,
  2335. in arbitrary order, or passed in registers (not pushed at all).
  2336. The order of evaluation may differ from the order in which
  2337. they are pushed.
  2338. One compiler may use several (incompatible) calling conventions.
  2339. .\"
  2340. .\" <side comment>
  2341. .\" One machine (??), for instance pushes R-to-L for compatibility
  2342. .\" with Pascal, except for varargs, which are passed L-to-R to
  2343. .\" make varargs work.  This always works since Pascal functions
  2344. .\" are never called varargs.
  2345. .\"
  2346. .IP \0\0\(bu
  2347. On some machines, the null character pointer
  2348. .Ep "((char *)0)"
  2349. is treated the same way as a pointer to a null string.
  2350. Do \fInot\fP depend on this.
  2351. .IP \0\0\(bu
  2352. Do not modify string constants\*f.
  2353. .FS
  2354. .IP \*F
  2355. Some libraries attempt to modify and then restore read-only
  2356. string variables.
  2357. Programs sometimes won't port because of these broken libraries.
  2358. The libraries are getting better.
  2359. .FE
  2360. .\"
  2361. .\" .FS
  2362. .\" .IP \*F
  2363. .\" Note that an initialzed array is writable.
  2364. .\" .Ex
  2365. .\" char s[] = "/dev/tty??";
  2366. .\" .Ee
  2367. .\" .FE
  2368. .\"
  2369. One particularly notorious (bad) example is
  2370. .Ex
  2371. s = "/dev/tty??";
  2372. strcpy (&s[8], ttychars);
  2373. .Ee
  2374. .IP \0\0\(bu
  2375. The address space may have holes.
  2376. Simply \fBcomputing\fP the address
  2377. of an unallocated element in an array
  2378. (before or after the actual storage of the array)
  2379. may crash the program.
  2380. If the address is used in a comparison,
  2381. sometimes the program will run but clobber data, give wrong answers,
  2382. or loop forever.
  2383. In \s-1ANSI\s+1 C, a pointer into an array of objects may legally point to
  2384. the first element after the end of the array; this is usually safe
  2385. in older implementations.
  2386. This ``outside'' pointer may not be dereferenced.
  2387. .\"
  2388. .\" K&R1 does not guarantee this behavior.  See K&R1, pg 188-9.
  2389. .\" Most implementations allow it, and it was standardized as a
  2390. .\" result.  On some machines, however, it fails.  For example,
  2391. .\" on an i80x86, no memory segments are 64k.  Addresses look like
  2392. .\" <segment,base>.  If N bytes are allocated and byte N+1 falls off
  2393. .\" the end of the segment, the base will wrap around to zero but stay
  2394. .\" in the same segment.  For example, adding 1 to <4,65535> gives
  2395. .\" <4,0>, so if &s[N-1] == <4,65535>, then &s[N] == <4,0>, which
  2396. .\" compares as LESS than the address of the N-1'th element.
  2397. .\"
  2398. .IP \0\0\(bu
  2399. Only the
  2400. .Ep =\^=
  2401. and
  2402. .Ep !\^=
  2403. comparisons are defined for all pointers of a given type.
  2404. It is only portable to use
  2405. .Ep < ,
  2406. .Ep <= ,
  2407. .Ep > ,
  2408. or
  2409. .Ep >= 
  2410. to compare pointers when they both point in to
  2411. (or to the first element after) the same array.
  2412. It is likewise only portable to use arithmetic operators on pointers
  2413. that both point into the same array or the first element afterwards.
  2414. .IP \0\0\(bu
  2415. Word size also affects shifts and masks.
  2416. The following code will clear only the three rightmost bits of an
  2417. \fIint\fP on \fIsome\fP 68000s.
  2418. On other machines it will also clear the upper two bytes.
  2419. .Ex
  2420. x &= 0177770
  2421. .Ee
  2422. Use instead
  2423. .Ex
  2424. x &= ~07
  2425. .Ee
  2426. which works properly on all machines.
  2427. .\"
  2428. .\" Originally, I'd said something like ``the or operator (\ |\ ) does
  2429. .\" not have these problems'', but that's not true.
  2430. .\" Consider
  2431. .\" .Ep "foo |= 0177770"
  2432. .\" vs.
  2433. .\" .Ep "foo |= ~07" 
  2434. .\".
  2435. Bitfields do not have these problems.
  2436. .IP \0\0\(bu
  2437. Side effects within expressions can result in code
  2438. whose semantics are compiler-dependent, since C's order of evaluation
  2439. is explicitly undefined in most places.
  2440. Notorious examples include the following.
  2441. .Ex
  2442. a[i] = b[i++];
  2443. .Ee
  2444. In the above example, we know only that
  2445. the subscript into
  2446. .Ep b
  2447. has not been incremented.
  2448. The index into
  2449. .Ep a
  2450. could be the value of
  2451. .Ep i
  2452. either before or after the increment.
  2453. .Ex
  2454. struct bar_t { struct bar_t *next; } bar;
  2455. bar->next = bar = tmp;
  2456. .Ee
  2457. In the second example, the address of
  2458. .Ep bar->next '' ``
  2459. may be computed before the value is assigned to
  2460. .Ep bar ''. ``
  2461. .Ex
  2462. bar = bar->next = tmp;
  2463. .Ee
  2464. In the third example,
  2465. .Ep bar
  2466. can be assigned before
  2467. .Ep bar->next.
  2468. Although this \fIappears\fP to violate the rule that
  2469. ``assignment proceeds right-to-left'', it is a legal interpretation.
  2470. Consider the following example:
  2471. .Ex
  2472. long i;
  2473. short a[N];
  2474. i = old
  2475. i = a[i] = new;
  2476. .Ee
  2477. The value that
  2478. .Ep i '' ``
  2479. is assigned must be a value that is typed as if assignment
  2480. proceeded right-to-left.
  2481. However,
  2482. .Ep i '' ``
  2483. may be assigned the value
  2484. .Ep "(long)(short)new" '' ``
  2485. before
  2486. .Ep a[i] '' ``
  2487. is assigned to.
  2488. Compilers do differ.
  2489. .\"
  2490. .\" More: if you write
  2491. .\" 
  2492. .\"         short b;
  2493. .\"         long a,c;
  2494. .\"          ...
  2495. .\"         a = b = c;
  2496. .\" 
  2497. .\" assignment ``proceeds AS IF right-to-left''.  The following is a
  2498. .\" legal implementation:
  2499. .\" 
  2500. .\"         b = (short) c;
  2501. .\"         a = (long) b;
  2502. .\" 
  2503. .\" A compiler is also allowed to implement it as:
  2504. .\" 
  2505. .\"         a = (long) (short) c;
  2506. .\"         b = (short) c;
  2507. .\" 
  2508. .\" since the same values are being assigned in each case.  But the
  2509. .\" assignment is not "proceeding right to left" in the second
  2510. .\" example, because a is assigned before b is.  This matters if b is
  2511. .\" replaced with an expression.
  2512. .\"
  2513. .IP \0\0\(bu
  2514. Be suspicious of numeric values appearing in the code (``magic
  2515. numbers'').
  2516. .IP \0\0\(bu
  2517. Avoid preprocessor tricks.
  2518. Tricks such as using
  2519. .Ep /**/
  2520. for token pasting
  2521. and macros that rely on argument string expansion will break reliably.
  2522. .Ex
  2523. #define FOO(string)    (printf("string = %s",(string)))
  2524. \&...
  2525. FOO(filename);
  2526. .Ee
  2527. Will only sometimes be expanded to
  2528. .Ex
  2529. (printf("filename = %s",(filename)))
  2530. .Ee
  2531. Be aware, however, that tricky preprocessors may cause macros to break
  2532. \fIaccidentally\fP on some machines.
  2533. Consider the following two versions of a macro.
  2534. .Ex
  2535. #define LOOKUP(chr)    (a['c'+(chr)])    /* Works as intended. */
  2536. #define LOOKUP(c)    (a['c'+(c)])        /* Sometimes breaks. */
  2537. .Ee
  2538. The second version of
  2539. .Ep LOOKUP
  2540. can be expanded in two different ways
  2541. and will cause code to break mysteriously.
  2542. .IP \0\0\(bu
  2543. Become familiar with existing library functions and defines.
  2544. (But not \fItoo\fP familiar.
  2545. The internal details of library facilities, as opposed to their
  2546. external interfaces, are subject to change without warning.
  2547. They are also often quite unportable.)
  2548. You should not be writing your own string compare routine,
  2549. terminal control routines, or making
  2550. your own defines for system structures.
  2551. ``Rolling your own'' wastes your time and
  2552. makes your code less readable, because another reader has to
  2553. figure out whether you're doing something special in that reimplemented
  2554. stuff to justify its existence.
  2555. It also prevents your program
  2556. from taking advantage of any microcode assists or other
  2557. means of improving performance of system routines.
  2558. Furthermore, it's a fruitful source of bugs.
  2559. If possible, be aware of the \fIdifferences\fP between the common 
  2560. libraries (such as \s-1ANSI\s+1, \s-1POSIX\s+1, and so on).
  2561. .IP \0\0\(bu
  2562. Use \fIlint\fP when it is available.
  2563. It is a valuable tool for finding machine-dependent constructs as well
  2564. as other inconsistencies or program bugs that pass the compiler.
  2565. If your compiler has switches to turn on warnings, use them.
  2566. .IP \0\0\(bu
  2567. Suspect labels inside blocks with the
  2568. associated
  2569. .Ec switch
  2570. or
  2571. .Ec goto
  2572. outside the block.
  2573. .IP \0\0\(bu
  2574. Wherever the type is in doubt,
  2575. parameters should be cast to the appropriate type.
  2576. Always cast NULL when it appears in non-prototyped function calls.
  2577. Do not use function calls as a place to do type cheating.
  2578. C has confusing promotion rules, so be careful.
  2579. For example, if a function expects a 32-bit
  2580. .Ec long
  2581. and it is passed a 16-bit
  2582. .Ec int
  2583. the stack can get misaligned, the value can get promoted wrong, etc.
  2584. .IP \0\0\(bu
  2585. Use explicit casts when doing arithmetic
  2586. that mixes signed and unsigned values.
  2587. .IP \0\0\(bu
  2588. The inter-procedural goto,
  2589. .Ec longjmp ,
  2590. should be used with caution.
  2591. Many implementations ``forget'' to restore values in registers.
  2592. Declare critical values as
  2593. .Ec volatile
  2594. if you can or comment them as
  2595. .Ep VOLATILE .
  2596. .IP \0\0\(bu
  2597. Some linkers convert names to lower-case
  2598. and
  2599. some only recognize the first six letters as unique.
  2600. Programs may break quietly on these systems.
  2601. .IP \0\0\(bu
  2602. Beware of compiler extensions.
  2603. If used, document and
  2604. consider them as machine dependencies.
  2605. .IP \0\0\(bu
  2606. .\"
  2607. .\" <interesting, but most folks don't care?>
  2608. .\"
  2609. A program cannot generally execute code in the data
  2610. segment or write into the code segment.
  2611. Even when it can, there is no guarantee that it can do so reliably.
  2612. .\"
  2613. .\" Examples: one 80386 default protection won't let you write to the
  2614. .\" code segment or execute from the data segment.  An 88000 will let
  2615. .\" you execute from the data segment, but unless the I-cache is told
  2616. .\" \fIexplicitly\fP to watch for invalidations, there is no way to
  2617. .\" tell when the I-cache will be updated.  As a result, some of the
  2618. .\" bytes of the cached instructions may be updated while others are
  2619. .\" left unchanged!
  2620. .\"
  2621. .NH
  2622. ANSI C
  2623. .PP
  2624. Modern C compilers support some or all of the \s-1ANSI\s+1 proposed standard
  2625. C.
  2626. Whenever possible, write code to run under standard C, and use
  2627. features such as function prototypes, constant storage, and volatile
  2628. storage.
  2629. Standard C improves program performance by giving better information
  2630. to optimizers.
  2631. Standard C improves portability by insuring that all compilers
  2632. accept the same input language and by providing mechanisms
  2633. that try to hide machine dependencies or emit warnings about
  2634. code that may be machine-dependent.
  2635. .NH 2
  2636. Compatibility
  2637. .PP
  2638. Write code that is easy to port to older compilers.
  2639. For instance,
  2640. conditionally #define new (standard) keywords such as
  2641. .Ec const
  2642. and
  2643. .Ec volatile
  2644. in a global \fI.h\fP file.
  2645. Standard compilers pre-define the preprocessor symbol
  2646. .Ep _\^\^_STDC_\^\^_ \*f.
  2647. .FS
  2648. .IP \*F
  2649. Some compilers predefine
  2650. .Ep _\^\^_STDC_\^\^_
  2651. to be 0, in an attempt to indicate partial compliance with the \s-1ANSI\s+1 C
  2652. standard.
  2653. Unfortunately, it is not possible to determine \fIwhich\fP \s-1ANSI\s+1
  2654. facilities are provided.
  2655. Thus, such compilers are broken.
  2656. See the rule about
  2657. ``don't write around a broken compiler unless you are forced to.''
  2658. .\"
  2659. .\" Although the 1989 \s-1ANSI\s+1 standard (X3.159-1989)
  2660. .\" defines _\^\^_STDC_\^\^_ as 1, later
  2661. .\" versions may define it to be another number.
  2662. .\"
  2663. .\" There's nothing keeping a vendor from defining __STDC__ to 0, or 1, or
  2664. .\" "hi" or anything else.  It is guaranteed that a conforming
  2665. .\" compiler will have __STDC__ set, and in particular that an
  2666. .\" \s-1ANSI\s+1-89-compliant compiler will set it to 1.  However, ``A implies
  2667. .\" B'' does not mean ``B implies A''.  That is, a nonconformant
  2668. .\" compiler can do anything it damn well pleases: interpret `while'
  2669. .\" to mean `abort compilation', rearrange expressions arbitrarily, or
  2670. .\" even set __STDC__ to zero.  Such usage is  broken because the
  2671. .\" vendor KNOWS that users are expecting __STDC__ to mean \s-1ANSI\s+1
  2672. .\" compliant and the vendor also KNOWS that the compiler isn't
  2673. .\" \s-1ANSI\s+1-compliant.
  2674. .\"
  2675. .FE
  2676. The
  2677. .Ec void*
  2678. type is hard to get right simply,
  2679. since some older compilers understand
  2680. .Ep void
  2681. but not
  2682. .Ep void* .
  2683. It is easiest to create a new
  2684. (machine- and compiler-dependent)
  2685. .Ep VOIDP
  2686. type, usually
  2687. .Ec char*
  2688. on older compilers.
  2689. .Ex
  2690. #if _\^\^_STDC_\^\^_
  2691.     typedef void *voidp;
  2692. #    define COMPILER_SELECTED
  2693. #endif
  2694. #ifdef A_TARGET
  2695. #    define const
  2696. #    define volatile
  2697. #    define void int
  2698.     typedef char *voidp;
  2699. #    define COMPILER_SELECTED
  2700. #endif
  2701. #ifdef ...
  2702.     \&...
  2703. #endif
  2704. #ifdef COMPILER_SELECTED
  2705. #    undef COMPILER_SELECTED
  2706. #else
  2707.     { NO TARGET SELECTED! }
  2708. #endif
  2709. .\"
  2710. .\" Alternatively, we could do
  2711. .\"
  2712. .\" #ifdef __STDC__
  2713. .\"    ..
  2714. .\" #    define CONST const
  2715. .\" #    define VOLATILE volatile
  2716. .\" #else
  2717. .\"    ..
  2718. .\" #endif
  2719. .\"
  2720. .\" Is one of these better?  Probably not, it will be a strange
  2721. .\" anachronism when everybody has forgotten that const once didn't
  2722. .\" exist.
  2723. .\"
  2724. .Ee
  2725. .PP
  2726. Note that under ANSI C, the `#' for a preprocessor directive must be
  2727. the first non-whitespace character on a line.
  2728. Under older compilers it must be the first character on the line.
  2729. .PP
  2730. When a static function has a forward declaration, the forward
  2731. declaration must include the storage class.
  2732. For older compilers, the class must be
  2733. .Ec extern ''. ``
  2734. For \s-1ANSI\s+1 compilers, the class must be
  2735. .Ec static ''. ``
  2736. but global functions must still be declared as
  2737. .Ec extern ''. ``
  2738. Thus, forward declarations of static functions should use a #define
  2739. such as
  2740. .Ep FWD_STATIC
  2741. that is #ifdeffed as appropriate.
  2742. .PP
  2743. An
  2744. .Ep "#ifdef NAME" '' ``
  2745. should end with either
  2746. .Ep #endif '' ``
  2747. or
  2748. .Ep "#endif /* NAME */" '', ``
  2749. \fInot\fP with
  2750. .Ep "#endif NAME" ''. ``
  2751. The comment should not be used on short #ifdefs,
  2752. as it is clear from the code.
  2753. .PP
  2754. ANSI
  2755. .Ec trigraphs
  2756. may cause programs with strings containing
  2757. .Ep ?? '' ``
  2758. may break mysteriously.
  2759. .\"
  2760. .\" ``sed -e "s;??\\([-=(/)'<!>]\\);?\\\\?\\1;g"
  2761. .\" will fix them...    -- Karl Heuer
  2762. .\"
  2763. .NH 2
  2764. Formatting
  2765. .PP
  2766. The style for \s-1ANSI\s+1 C is the same as for regular C,
  2767. with two notable exceptions: storage qualifiers
  2768. and parameter lists.
  2769. .PP
  2770. Because
  2771. .Ep const
  2772. and
  2773. .Ep volatile
  2774. have strange binding rules,
  2775. .\"
  2776. .\" In particular, "char const *s, *t" means both `t' and `s' point
  2777. .\" to constant storage, while "char * const s, *t" means that s is
  2778. .\" a constant, but `t' isn't.
  2779. .\"
  2780. .\" I think.
  2781. .\"
  2782. .\" `*' binds differently than `const'.
  2783. .\"
  2784. each
  2785. .Ec const
  2786. or
  2787. .Ec volatile
  2788. object should have a separate declaration.
  2789. .Ex
  2790. int const *s;        /* YES */
  2791. int const *s, *t;    /* NO */
  2792. .Ee
  2793. .PP
  2794. Prototyped functions merge parameter declaration
  2795. and definition in to one list.
  2796. Parameters should be commented in the function comment.
  2797. .Ex
  2798. /*
  2799.  * `bp': boat trying to get in.
  2800.  * `stall': a list of stalls, never NULL.
  2801.  * returns stall number, 0 => no room.
  2802.  */
  2803.     int
  2804. enter_pier (boat_t const *bp, stall_t *stall)
  2805. {
  2806.     \&...
  2807. .Ee
  2808. .\" .NH 2
  2809. .\" Storage Qualifiers
  2810. .NH 2
  2811. Prototypes
  2812. .PP
  2813. Function prototypes should be used
  2814. to make code more robust and to make it run faster.
  2815. Unfortunately, the prototyped \fBdeclaration\fP
  2816. .Ex
  2817. extern void bork (char c);
  2818. .Ee
  2819. is incompatible with the \fBdefinition\fP
  2820. .Ex
  2821.     void
  2822. bork (c)
  2823.     char c;
  2824. \&...
  2825. .Ee
  2826. The prototype says that
  2827. .Ep c
  2828. is to be passed as the most natural type for the machine,
  2829. possibly a byte.
  2830. The non-prototyped (backwards-compatible) definition implies that
  2831. .Ep c
  2832. is always passed as an
  2833. .Ec int \*f.
  2834. .FS
  2835. .IP \*F
  2836. Such automatic type promotion is called
  2837. .Ec widening .
  2838. For older compilers, the widening rules require that
  2839. all
  2840. .Ec char
  2841. and
  2842. .Ec short
  2843. parameters are passed as
  2844. .Ec int s
  2845. and that
  2846. .Ec float
  2847. parameters are passed as
  2848. .Ec double s.
  2849. .FE
  2850. If a function has promotable parameters then 
  2851. the caller and callee must be compiled identically.
  2852. Either both must use function prototypes
  2853. or neither can use prototypes.
  2854. The problem can be avoided if parameters are promoted when the program
  2855. is designed.
  2856. For example,
  2857. .Ep bork
  2858. can be defined to take an
  2859. .Ec int
  2860. parameter.
  2861. .PP
  2862. The above declaration works if the definition is prototyped.
  2863. .Ex
  2864.     void
  2865. bork (char c)
  2866. {
  2867.     \&...
  2868. .Ee
  2869. Unfortunately,
  2870. the prototyped syntax will cause non-\s-1ANSI\s+1 compilers to reject the
  2871. program.
  2872. .\"
  2873. .\" There is no obvious way to define the function so that
  2874. .\" prototypes are used only when an \s-1ANSI\s+1 compiler is used.
  2875. .\" Prototyped and nonprototyped declarations can be #ifdeffed on
  2876. .\" .Ep _\^\^_STDC_\^\^_ ,
  2877. .\" but the extra #ifdeffing causes maintainance problems
  2878. .\" and makes the code hard to read.
  2879. .\"
  2880. .\" Oh yeah, try
  2881. .\"
  2882. .\"    int DEFUN (foo, (a, p), int a AND char *p)
  2883. .\"    int foo FUN2(int, a, char *, p)
  2884. .\"
  2885. .\" But beware: ``Don't change the syntax via macro substitution.''
  2886. .\"
  2887. .PP
  2888. It \fIis\fP easy to write external declarations that work with both
  2889. prototyping and with older compilers\*f.
  2890. .FS
  2891. .IP \*F
  2892. Note that using
  2893. .Ep PROTO
  2894. violates the rule ``don't change the syntax via macro substitution.''
  2895. It is regrettable that there isn't a better solution.
  2896. .FE
  2897. .Ex
  2898. #if _\^\^_STDC_\^\^_
  2899. #    define PROTO\^(x) x
  2900. #else
  2901. #    define PROTO\^(x) (\^)
  2902. #endif
  2903.  
  2904. extern char **ncopies PROTO((char *s, short times));
  2905. .Ee
  2906. Note that
  2907. .Ep PROTO
  2908. must be used with \fIdouble\fP parentheses.
  2909. .PP
  2910. In the end,
  2911. it may be best to write in only one style (e.g., with prototypes).
  2912. When a non-prototyped version is needed, it is generated using an
  2913. automatic conversion tool.
  2914. .NH 2
  2915. Pragmas
  2916. .PP
  2917. Pragmas
  2918. are used to introduce machine-dependent code in a controlled way.
  2919. Obviously, pragmas should be treated as machine dependencies.
  2920. Unfortunately, the syntax of \s-1ANSI\s+1 pragmas
  2921. makes it impossible to isolate them in machine-dependent headers.
  2922. .\"
  2923. .\" <side note>
  2924. .\" Because it is of the form ``#pragma'' instead of ``pragma(args)''.
  2925. .\" You can't put the #pragma in an include file, as it will get
  2926. .\" interpreted there.
  2927. .\"
  2928. .\" You are also prevented from embedding pragmas in macros.
  2929. .\"
  2930. .PP
  2931. Pragmas are of two classes.
  2932. .Ec Optimizations
  2933. may safely be ignored.
  2934. Pragmas that change the system behavior (``required pragmas'')
  2935. may not.
  2936. Required pragmas should be #ifdeffed so that compilation will abort if
  2937. no pragma is selected.
  2938. .PP
  2939. Two compilers may use a given pragma in two very different ways.
  2940. For instance, one compiler may use
  2941. .Ep haggis '' ``
  2942. to signal an optimization.
  2943. Another might use it to indicate that a given statement,
  2944. if reached, should terminate the program.
  2945. Thus, when pragmas are used,
  2946. they must always be enclosed in machine-dependent #ifdefs.
  2947. Pragmas must always be #ifdefed out for non-\s-1ANSI\s+1 compilers.
  2948. Be sure to indent the `#' character on the
  2949. .Ep #pragma ,
  2950. as older preprocessors will halt on it otherwise.
  2951. .Ex
  2952. #if defined(_\^\^_STDC_\^\^_) && defined(USE_HAGGIS_PRAGMA)
  2953.     #pragma (HAGGIS)
  2954. #endif
  2955. .Ee
  2956. .QP
  2957. ``\fIThe `#pragma' command is specified in the \s-1ANSI\s+1 standard to have an
  2958. arbitrary implementation-defined effect.
  2959. In the GNU C preprocessor, `#pragma' first attempts to run the game
  2960. `rogue'; if that fails, it tries to run the game `hack'; if that
  2961. fails, it tries to run GNU Emacs displaying the Tower of Hanoi; if
  2962. that fails, it reports a fatal error.
  2963. In any case, preprocessing does not continue.\fP''
  2964. .br
  2965. .ad r
  2966. \(em Manual for the GNU C preprocessor for GNU CC 1.34.
  2967. .br
  2968. .ad b
  2969. .\" NEED MORE STUFF!!
  2970. .NH
  2971. Special Considerations
  2972. .PP
  2973. This section contains some miscellaneous do's and don'ts.
  2974. .\"
  2975. .\" This should probably be either "dos and don'ts" or
  2976. .\" "do's and don't's", but neither looks quite right.
  2977. .\"
  2978. .IP \0\0\(bu
  2979. Don't change syntax via macro substitution.
  2980. It makes the program unintelligible to all but the perpetrator.
  2981. .IP \0\0\(bu
  2982. Don't use floating-point variables where discrete values are needed.
  2983. Using a
  2984. .Ec float
  2985. for a loop counter is a great way to shoot yourself in the foot.
  2986. Always test floating-point numbers as \fB<=\fP or \fB>=\fP,
  2987. never use an exact comparison (\fB=\^=\fP or \fB!=\fP\&).
  2988. .IP \0\0\(bu
  2989. Compilers have bugs.
  2990. Common trouble spots include structure assignment and bitfields.
  2991. You cannot generally predict which bugs a compiler has.
  2992. You \fIcould\fP write a program that avoids all constructs that are
  2993. known broken on all compilers.
  2994. You won't be able to write anything useful,
  2995. you might still encounter bugs,
  2996. and the compiler might get fixed in the meanwhile.
  2997. Thus, you should write ``around'' compiler bugs only when you are
  2998. \fIforced\fP to use a particular buggy compiler.
  2999. .IP \0\0\(bu
  3000. Do not rely on automatic beautifiers.
  3001. The main person who benefits from good program style is the
  3002. programmer him/herself,
  3003. and especially in the early design of handwritten algorithms
  3004. or pseudo-code.
  3005. Automatic beautifiers can only be applied to complete, syntactically
  3006. correct programs and hence are not available when the need for
  3007. attention to white space and indentation is greatest.
  3008. Programmers can do a better job of making clear
  3009. the complete visual layout of a function or file, with the normal
  3010. attention to detail of a careful programmer.
  3011. (In other words, some of the visual layout is dictated by intent
  3012. rather than syntax
  3013. and beautifiers cannot read minds.)
  3014. Sloppy programmers should learn to be careful programmers instead of
  3015. relying on a beautifier to make their code readable.
  3016. .\"
  3017. .\" Finally, beautifiers are nontrivial, can have bugs, and never do a
  3018. .\" perfect job.
  3019. .\" Also, beautifiers do things such as silently taking
  3020. .\" .Ep x=-1;
  3021. .\" to be old-style syntax for
  3022. .\" .Ep x -= 1;
  3023. .\" even though that might not be what is wanted, and
  3024. .\" such a conversion is \fIwrong\fP for ANSI-C input.
  3025. .\"
  3026. .IP \0\0\(bu
  3027. Accidental omission of the second
  3028. .Ep = '' ``
  3029. of the logical compare is a problem.
  3030. Use explicit tests.
  3031. Avoid assignment with implicit test.
  3032. .Ex
  3033. abool = bbool;
  3034. if (abool) { ...
  3035. .Ee
  3036. When embedded assignment \fIis\fP used, make the test explicit
  3037. so that it doesn't get ``fixed'' later.
  3038. .Ex
  3039. while ((abool = bbool) != FALSE) { ...
  3040. .Ee
  3041. .Ex
  3042. while (abool = bbool) { ...    /* VALUSED */
  3043. .Ee
  3044. .Ex
  3045. while (abool = bbool, abool) { ...
  3046. .Ee
  3047. .\"
  3048. .\" I happen to think the following is ugly, but it works if one of
  3049. .\" the values is a constant.
  3050. .\" The ``trick'' is to put a non-lvalue on the lhs.
  3051. .\" The compiler then barfs if an
  3052. .\" .Ep = '' ``
  3053. .\" is typed instead of the intended
  3054. .\" .Ep =\^= ''. ``
  3055. .\"
  3056. .\" .Ex
  3057. .\" if (2 == i) {...}
  3058. .\" .Ee
  3059. .\"
  3060. .IP \0\0\(bu
  3061. Explicitly comment
  3062. variables that are changed out of the normal control flow,
  3063. or other code that is likely to break during maintenance.
  3064. .IP \0\0\(bu
  3065. Modern compilers will put variables in registers automatically.
  3066. Use the
  3067. .Ec register
  3068. sparingly to indicate the variables that you think are most critical.
  3069. In extreme cases, mark the 2-4 most critical values as
  3070. .Ep register
  3071. and mark the rest as
  3072. .Ep REGISTER.
  3073. The latter can be #defined to
  3074. .Ep register
  3075. on those machines with many registers.
  3076. .NH
  3077. Lint
  3078. .PP
  3079. \fILint\fP is a C program checker [2][11] that examines C source files
  3080. to detect and report type incompatibilities, inconsistencies between
  3081. function definitions and calls,
  3082. potential program bugs, etc.
  3083. The use of \fIlint\fP on all programs is strongly recommended,
  3084. and it is expected that most projects will require programs to use
  3085. \fIlint\fP as part of the official acceptance procedure.
  3086. .PP
  3087. It should be noted that the best way to use \fIlint\fP is not as a
  3088. barrier that must be overcome before official acceptance of a program,
  3089. but rather as a tool to use during and after changes or additions to
  3090. the code.
  3091. \fILint\fP
  3092. can find obscure bugs and insure portability before problems occur.
  3093. Many messages from \fIlint\fP really do indicate something wrong.
  3094. One fun story is about is about a program that was missing
  3095. an argument to
  3096. .Ep fprintf '. `
  3097. .Ex
  3098. fprintf ("Usage: foo -bar <file>\\\en");
  3099. .Ee
  3100. The \fIauthor\fP never had a problem.
  3101. But the program dumped core every time an ordinary user made a mistake
  3102. on the command line.
  3103. Many versions of \fIlint\fP will catch this.
  3104. .PP
  3105. Most options are worth learning.
  3106. Some options may complain about legitimate things, but they will
  3107. also pick up many botches.
  3108. Note that \-p\*f
  3109. .FS
  3110. .IP \*F
  3111. Flag names may vary.
  3112. .FE
  3113. checks function-call type-consistency for only a subset
  3114. of library routines, so programs should be linted both with and
  3115. without \-p for the best ``coverage''.
  3116. .PP
  3117. \fILint\fP also recognizes several special comments in the code.
  3118. These comments both shut up \fIlint\fP when the code
  3119. otherwise makes it complain,
  3120. and also document special code.
  3121. .NH
  3122. Make
  3123. .PP
  3124. One other very useful tool is \fImake\fP [7].
  3125. During development,
  3126. \fImake\fP recompiles only those modules that have been changed
  3127. since the last time \fImake\fP was used.
  3128. It can be used to automate other tasks, as well.
  3129. Some common conventions include:
  3130. .TS
  3131. center;
  3132. r l.
  3133. all    \fIalways\fP makes all binaries
  3134. clean    remove all intermediate files
  3135. debug    make a test binary 'a.out' or 'debug'
  3136. depend    make transitive dependencies
  3137. install    install binaries, libraries, etc.
  3138. deinstall    back out of ``install''
  3139. mkcat    install the manual page(s)
  3140. lint    run lint
  3141. print/list    make a hard copy of all source files
  3142. shar    make a shar of all source files
  3143. spotless    make clean, use revision control to put away sources.
  3144.     Note: doesn't remove Makefile, although it is a source file
  3145. source    undo what spotless did
  3146. tags    run ctags, (using the -t flag is suggested)
  3147. rdist    distribute sources to other hosts
  3148. \fIfile.c\fP    check out the named file from revision control
  3149. .TE
  3150. In addition, command-line defines
  3151. can be given to define either Makefile values
  3152. (such as ``CFLAGS'')
  3153. or values in the program
  3154. (such as ``DEBUG'').
  3155. .NH
  3156. Project-Dependent Standards
  3157. .PP
  3158. Individual projects may wish to establish additional standards beyond
  3159. those given here.
  3160. The following issues are some of those that should be addressed by
  3161. each project program administration group.
  3162. .IP \0\0\(bu
  3163. What additional naming conventions should be followed?
  3164. In particular, systematic prefix conventions for functional grouping
  3165. of global data and also for structure or union member names can be
  3166. useful.
  3167. .IP \0\0\(bu
  3168. What kind of include file organization is appropriate for the
  3169. project's particular data hierarchy?
  3170. .IP \0\0\(bu
  3171. What procedures should be established for reviewing \fIlint\fP
  3172. complaints?
  3173. A tolerance level needs to be established in concert with the \fIlint\fP
  3174. options to prevent unimportant complaints from hiding complaints about
  3175. real bugs or inconsistencies.
  3176. .IP \0\0\(bu
  3177. If a project establishes its own archive libraries, it should plan on
  3178. supplying a lint library file [2] to the system administrators.
  3179. The lint library file allows \fIlint\fP to check for compatible use of
  3180. library functions.
  3181. .IP \0\0\(bu
  3182. What kind of revision control needs to be used?
  3183. .NH
  3184. Conclusion
  3185. .PP
  3186. A set of standards has been presented for C programming style.
  3187. Among the most important points are:
  3188. .IP \0\0\(bu
  3189. The proper use of white space and comments
  3190. so that the structure of the program is evident from
  3191. the layout of the code.
  3192. The use of simple expressions, statements, and functions
  3193. so that they may be understood easily.
  3194. .IP \0\0\(bu
  3195. To keep in mind that
  3196. you or someone else will likely be asked to modify code or make
  3197. it run on a different machine sometime in the future.
  3198. Craft code so that it is portable to obscure machines.
  3199. Localize optimizations since they are often confusing
  3200. and may be ``pessimizations'' on other machines.
  3201. .IP \0\0\(bu
  3202. Many style choices are arbitrary.
  3203. Having a style that is consistent
  3204. (particularly with group standards)
  3205. is more important than following absolute style rules.
  3206. Mixing styles is worse than using any single bad style.
  3207. .PP
  3208. As with any standard, it must be followed if it is to be useful.
  3209. If you have trouble following any of these standards
  3210. don't just ignore them.
  3211. Talk with your local guru,
  3212. or an experienced programmer at your institution.
  3213. .bp
  3214. .ce 1
  3215. \fBReferences\fP
  3216. .sp 2
  3217. .IP [1]
  3218. B.A. Tague, \fIC Language Portability\fP, Sept 22, 1977.
  3219. This document issued by department 8234 contains three memos by
  3220. R.C. Haight, A.L. Glasser, and T.L. Lyon dealing with style and
  3221. portability.
  3222. .IP [2]
  3223. S.C. Johnson, \fILint, a C Program Checker\fP,
  3224. \s-1USENIX\s+1
  3225. .UX
  3226. Supplementary Documents, November 1986.
  3227. .IP [3]
  3228. R.W. Mitze, \fIThe 3B/PDP-11 Swabbing Problem\fP, Memorandum for File,
  3229. 1273-770907.01MF,
  3230. September 14, 1977.
  3231. .IP [4]
  3232. R.A. Elliott and D.C. Pfeffer, \fI3B Processor Common Diagnostic
  3233. Standards- Version 1\fP,
  3234. Memorandum for File, 5514-780330.01MF, March 30, 1978.
  3235. .IP [5]
  3236. R.W. Mitze,
  3237. \fIAn Overview of C Compilation of
  3238. .UX
  3239. User Processes on the 3B\fP,
  3240. Memorandum for File, 5521-780329.02MF, March 29, 1978.
  3241. .IP [6]
  3242. B.W. Kernighan and D.M. Ritchie,
  3243. \fIThe C Programming Language\fP,
  3244. Prentice Hall 1978,
  3245. Second Ed. 1988, \s-1ISBN\s+1 0-13-110362-8.
  3246. .IP [7]
  3247. S.I. Feldman,
  3248. \fIMake \(em A Program for Maintaining Computer Programs\fP,
  3249. \s-1USENIX\s+1
  3250. .UX
  3251. Supplementary Documents, November 1986.
  3252. .IP [8]
  3253. Ian Darwin and Geoff Collyer,
  3254. \fICan't Happen or /* NOTREACHED */ or Real Programs Dump Core\fP,
  3255. \s-1USENIX\s+1 Association Winter Conference, Dallas 1985 Proceedings.
  3256. .IP [9]
  3257. Brian W. Kernighan and P. J. Plauger
  3258. \fIThe Elements of Programming Style\fP.
  3259. McGraw-Hill, 1974, Second Ed. 1978, \s-1ISBN\s+1 0-07-034-207-5.
  3260. .IP [10]
  3261. J. E. Lapin
  3262. \fIPortable C and U\s-1NIX\s+1 System Programming\fP,
  3263. Prentice Hall 1987,
  3264. \s-1ISBN\s+1 0-13-686494-5.
  3265. .IP [11]
  3266. Ian F. Darwin,
  3267. \fIChecking C Programs with lint\fP,
  3268. O'Reilly & Associates, 1989.
  3269. \s-1ISBN\s+1 0-937175-30-7.
  3270. .IP [12]
  3271. Andrew R. Koenig,
  3272. \fIC Traps and Pitfalls\fP,
  3273. Addison-Wesley, 1989.
  3274. \s-1ISBN\s+1 0-201-17928-8.
  3275. .\" .IP []
  3276. .\" Samuel P. Harbison and Guy L. Steele Jr.
  3277. .\" \fIC: A Reference Manual\fP
  3278. .\" 1984, 1987
  3279. .\" \s-1ISBN\s+1 is 0-13-109802-0
  3280. .\" .Ee
  3281. .\" .IP []
  3282. .\" Mark Horton
  3283. .\" \fIPortable C Software\fP
  3284. .\" Prentice-Hall, Englewood Cliffs NJ
  3285. .\" 1990
  3286. .\" \s-1ISBN\s+1 is 0-13-868050-7
  3287. .\" .Ee
  3288. .bp
  3289. \s+1
  3290. .ce
  3291. \fBThe Ten Commandments for C Programmers\fP
  3292. \s-1
  3293. .sp 2
  3294. .ce
  3295. \fIHenry Spencer\fP
  3296. .sp 2
  3297. .IP 1
  3298. Thou shalt run \fIlint\fP frequently and study its pronouncements with
  3299. care, for verily its perception and judgement oft exceed thine.
  3300. .IP 2
  3301. Thou shalt not follow the NULL pointer,
  3302. for chaos and madness await thee at its end.
  3303. .IP 3
  3304. Thou shalt cast all function arguments to the expected type
  3305. if they are not of that type already,
  3306. even when thou art convinced that this is unnecessary,
  3307. lest they take cruel vengeance upon thee when thou least expect it.
  3308. .IP 4
  3309. If thy header files fail to declare the return types
  3310. of thy library functions,
  3311. thou shalt declare them thyself with the most meticulous care,
  3312. lest grievous harm befall thy program.
  3313. .IP 5
  3314. Thou shalt check the array bounds of all strings (indeed, all arrays),
  3315. for surely where thou typest ``foo'' someone someday shall type
  3316. ``supercalifragilisticexpialidocious''.
  3317. .IP 6
  3318. If a function be advertised to return an error code in the event of
  3319. difficulties,
  3320. thou shalt check for that code, yea, even though the checks
  3321. triple the size of thy code and produce aches in thy typing fingers,
  3322. for if thou thinkest ``it cannot happen to me'',
  3323. the gods shall surely punish thee for thy arrogance.
  3324. .IP 7
  3325. Thou shalt study thy libraries and strive not to re-invent them
  3326. without cause,
  3327. that thy code may be short and readable and thy days pleasant and
  3328. productive.
  3329. .IP 8
  3330. Thou shalt make thy program's purpose and structure
  3331. clear to thy fellow man by using the
  3332. One True Brace Style,
  3333. even if thou likest it not,
  3334. for thy creativity is better used in solving problems than in creating
  3335. beautiful new impediments to understanding.
  3336. .IP 9
  3337. Thy external identifiers shall be unique in the first six characters,
  3338. though this harsh discipline be irksome and the years of its necessity
  3339. stretch before thee seemingly without end,
  3340. lest thou tear thy hair out and go mad on that fateful day when
  3341. thou desirest to make thy program run on an old system.
  3342. .IP 10
  3343. Thou shalt foreswear, renounce,
  3344. and abjure the vile heresy which claimeth
  3345. that ``All the world's a VAX'', and have no commerce with the
  3346. benighted heathens who cling to this barbarous belief,
  3347. that the days of thy program may be long even though the days of thy
  3348. current machine be short.
  3349.