\documentstyle[twoside]{report}
\pagestyle{headings}
%****
% Temporary -- we need to change the chapter heading so it
%		uses \huge size, rather than \Huge (which
%		is missing on REX::)
% \@makechapterhead{} and \@makeschapterhead{} were copied
% from tex$inputs:report.doc.
%****
\makeatletter		% make @ a letter for "internal" macros
% \@makechapterhead {TEXT} : Makes the heading for the \chapter command.
%

\def\@makechapterhead#1{             % Heading for \chapter command
  \vspace*{50pt}                     % Space at top of text page.
  { \parindent 0pt \raggedright 
    \huge \@chapapp{} \thechapter % 'Chapter' and number.
    \par 
    \vskip 20pt                      % Space between number and title.
    \huge                            % Title.
    #1\par 
    \nobreak                         % TeX penalty to prevent page break.
    \vskip 40pt                      % Space between title and text.
  } }

% \@makeschapterhead {TEXT} : Makes the heading for the \chapter* command.
%

\def\@makeschapterhead#1{             % Heading for \chapter* command
  \vspace*{50pt}                     % Space at top of page.
  { \parindent 0pt \raggedright 
    \huge                            % Title.
    #1\par 
    \nobreak                         % TeX penalty to prevent page break.
    \vskip 40pt                      % Space between title and text.
  } }
\makeatother		% Turn off the special definition of @
%****
% End of temporary stuff
%***
%%
%
\font\triumlogo=triumlogo		% Chicklets logo
\font\triub=triub			% for "digital"
%
% Redefine some layout parameters:
%
\renewcommand{\labelitemii}{$\bullet$}	% Second-level \item
\parskip 3pt plus 2pt minus 1pt		% this looks better than
\parindent 20pt				% the standard style
%
% Use \Head to set page headings -- a good idea whose time has gone.
%
%% \addtolength{\headheight}{15pt}	% Make room for Chicklets logo
%%\newcommand{\Head}[1]{
%%  \head[l]{~~\Digital \hfill #1}
%%  \head[r]{#1 \hfill \Digital~~}
%%}
\newcommand{\SECT}[1]{
%%  \Head{#1}
\typeout{#1}
\section{#1}
}
%
% This command is used to cite quotations.  It is used by
% ... foobar.\CITE{Moe, Larry, and Shep}{UNIX for the rest
% of us}{p. 104}
% Note that you must supply the author, the title, and the 
% page reference as either {p. 123} or {pp. 123-456}.
%
\newcommand{\CITE}[3]{\footnote{#1, ``UNIX Time-Sharing System: #2,''
  B.S.T.J., {\it vol\/}. 57, {\it no\/}. 6, {\it part 2\/}
  (July-August 1978), #3{}.}}
%
% The \NAME macro should generate program names in Bold-face sans-serif.
%
\newcommand{\NAME}[1]{{\bf \tt  #1}}
%
% Redefine some things for descriptions
%
% \DesSize{longtext} should be executed before each description.  It sets
% the item indentation to suit the longest element's size.
%
\newlength{\DesWidthMin}		% Default minimum item indentation
\newlength{\DesWidthMax}		% Default maximum item indentation
\setlength{\DesWidthMin}{\descriptionmargin}	% Set minimum item indent
\setlength{\DesWidthMax}{.25\linewidth}		% Set maximum item indent
\newcommand{\DesSize}[1]{\settowidth{\descriptionmargin}{{#1~~}}
  \ifdim \descriptionmargin >\DesWidthMax
	\setlength{\descriptionmargin}{\DesWidthMax}
  \fi
  \ifdim \descriptionmargin <\DesWidthMin
	\setlength{\descriptionmargin}{\DesWidthMin}
  \fi
}
\renewcommand{\descriptionlabel}[1]{#1\hfill}
%
% Define textual macros:
% \_		not correct in standard TeX for big fonts
% \Digital	The Chicklets logo
%
\renewcommand{\_}{{\tt \char95}}
\newcommand{\Digital}{{\triumlogo\char'012\char'010\char'007\char'006}}
%
% Define  special list environments that don't reset
% the right margin.  \begin{setoff} ... \end{setoff} indents
% the bounded text by an appropriate amount.
% \begin{vsetoff} ... \end{vsetoff} are intended to be
% used as follows:
%	\begin{footnotesize} \begin{vsetoff} \begin{verbatim}
%	   ...
%	\end{verbatim} \end{vsetoff} \end{footnotesize}
% \begin{vsetoff} is also useful for setting notes without
% the paragraph skip of \begin{setoff}
%
% newenvironment takes 3 parameters:
%	environment name	setoff
%	executed at env. start	\list{}{}\item[]
%	executed at env. end	\endlist
\newenvironment{setoff}{\list{}{}\item[]}{\endlist}
\newenvironment{vsetoff}{\list{}{\setlength{\topsep}{0in}}\item[]}{\endlist}
\newcommand{\SETOFFSIZE}{}	% Place to hang \footnotesize
%
\begin{document}
\begin{titlepage}
 \Digital \par
 \vskip 20pt
 \begin{center}
   {\huge Notes on C Style \par}
   {\large by \par }
   {\large Martin Minow \par }
   {Digital Equipment Corporation \par}
   {Maynard, Mass., U. S. A. \par}
   \vskip 3em				% Vertical space after subtitle.
   {\Large Summary \par}
\end{center}

\noindent
This document describes a coding style for C programs.  It was compiled
from a number of sources, especially a set of
UNIX\footnote{UNIX is a trademark of A.T.\&T. Bell Laboratories}
guidelines called the ``Indian Hill C Style and Coding Standards.''
\vfill
\begin{center} {\triumlogo
  Copyright \raisebox{.2ex}{\sf \copyright{}} 1985 by \smallskip \\
  {\triub digital equipment corporation } \\
  {\triub maynard, massachusetts \medskip } \\
  All Rights Reserved \\
  Printed in U.S.A. \\
} \end{center}
\vfill
\begin{quote}
This document was produced using the \LaTeX{} document
preparation system developed by Leslie
Lamport.  All page composition and make-up was performed
by \TeX\footnote{\TeX{} is a registered trademark of the
American Mathematical Society.}, the typesetting system developed by
Donald E. Knuth at Stanford University.
\end{quote}
\end{titlepage}
\newpage
\tableofcontents
\newpage
\chapter{A C Style Sheet}
\SECT{Introduction}

This document presents a common set of coding standards, as well as a
series of hints to aid in producing maintainable and transportable C
software.  It is abstracted from a number of sources:

\begin{itemize}

\item Brian Kernighan and Dennis Ritchie. {\it The C Programming Language.}

\item L. W. Cannon, R. A. Elliott, L. W. Kirchoff, J. H. Miller,
J. M. Milner, R. W. Mitze, E. P. Schan, N. O. Whittington.
{\it Indian Hill C Style and Coding Standards\/} (Bell Telephone
Labs unpublished Technical Memorandum 78-5221, March 29, 1978) with
annotations by Henry Spencer (\verb'utzoo!henry'), University of
Toronto.

\item Joe Kalish. {\it Ingres Coding Conventions for C/Unix Programming\/}
(\verb'INGVAX.kalish@Berkeley')

\item Dan Franklin.  {\it BBN Programming Standards for C.\/}
(\verb'Dan@BBN-UNIX')

\item Andrew Shore, et al. {\it Network Graphics C Style Sheet.\/}
Stanford University, (distributed by \verb'CSL.LANTZ@SU-SCORE').

\item Ray Van Tassle.  {\it C Language Programming Standards for
Motorola DCS.\/}  Motorola, Inc.  1301 E. Algonquin Road, Room 4135,
Schaumburg, IL 60196.

\end{itemize}

It is also based heavily on my own experience in developing a number of
large, transportable, applications in C, using Decus C, VaxC, and
several varieties of UNIX C.

As could be expected, the suggested style does not totally agree with
any of the referenced documents.

\SECT{Motivation}

The reason you should maintain a consistant coding style is that good
programs will evolve.  When writing a new program, you will often take
routines and data structures from old--working--software. This is much
easier to do if the old software is understandable. Unreadable software
is unusable, no matter how well it works.

The single most important thing about a typographical style is sticking
to it consistently.  There are many good styles, but the differences
among them are totally drowned out by the difficulty of reading a
program with pieces in different styles.  If you modify a program, stick
to its original style.  If you \underline{must} change things--you
really cannot live with the old style--change the whole program, or at
least all the parts logically related to what you are changing.

In recommending against automatic beautifiers (prettyprinters), the
Indian Hill standards committee noted:

\begin{quote}
First, the main person who benefits from good program style is the
programmer himself.  This is especially true in the early design of
handwritten algorithms or pseudo-code.  Automatic beautifiers ... are
not available when the need for attention to white space and indentation
is greatest. It is also felt that programmers can do a better job of
making clear the complete visual layout of a function or a file with the
normal attention to detail of a careful programmer.
\end{quote}

These comments are relevant to any rigid application of a programming or
typographical style.  There will always be cases where the automatic
rule is unsatisfactory and you, as the person responsible, must be able
to understand that your primary goal is to achieve clarity and
understandability.

\SECT{File Organization}

A file consists of several sections separated by blank lines or a
form-feed (\verb'<FF>').  If you use a form-feed, it should be the only
character on the line.

In general, source files should not be much longer than 1000 lines.
Larger files are often difficult to edit and--if too large--cannot be
processed by the \NAME{diff}{} (differences) program.  1000 lines
translates to about 12-15 pages of text.  Source lines should not be
longer than 78 characters long.

A source file should be organized as follows:
\DesSize{~~~~}
\begin{description}
\item[\underline{A prologue}] comment gives the file name and a few
sentences telling what is in the file. This is followed, if necessary,
by copyright and license ``boilerplate.'' The prologue tells the reader
the purpose of the text of the file, whether it contains functions, data
definitions, tables, or support code.  It should not generally be a list
of function names.

In some programs, C source files may be created by program generators.
For example, a dictionary may be compiled into a keyword vector (one
file) and a definition vector (one file).  In this case, the program
generating the files should write the date of generation (as a comment)
into the C file source.  If the generated program file may require
editing, consider including the source of the generated information,
either as comments or as text bracketed by \verb'#ifdef', as an aid to
the debugger.

\item[\underline{Usage and operating instructions}] follow next.  Decus C
programs should use the format accepted by the \NAME{getrno}{} utility
program. This allows the program source file to contain the source of
its documentation and lessens the burden of keeping the documentation in
synchronization with the program itself.

If a program is composed from separate modules, one of the modules
(generally the one with the \verb'main()' function) should contain instructions
on how to build the program.

Decus C programs should use the build utility to maintain compilation
instructions:
\begin{vsetoff}  \begin{verbatim}
/*)BUILD
    $(PROGRAM) = program
    $(INCLUDE) = header.h
    $(FILES)   = { file1 file2 }
*/
\end{verbatim} \end{vsetoff}

UNIX programs should include a separate \verb'Makefile' with commands to
compile and maintain the program. This centralizes everything relevant
to maintainence of a program in one place.

\item[\underline{Header files}] are specified using the \verb'#include'
preprocessor directive. The suggested header file order is
\begin{vsetoff}  \begin{verbatim}
    #include <stdio.h>
    #include <other system headers>
    #include "user header files"
\end{verbatim} \end{vsetoff} 

Note that header files should be given the ``\verb'.h''' filetype, while
all C source files should be given the ``\verb'.c''' filetype.

In allocating header files for large packages of programs, you should
avoid absolute pathnames for header files.  Use the \verb'<name>'
construction for system files, relative directories for Unix and VMS
systems, and externally defined logical devices for RSTS/E and RT11.  If
the sub-system is reasonably small, put all source files in one
directory.

\item[\underline{\NAME{typedef}, {\tt \char"23 define} and structure
definitions}] that apply to the file as a whole are next.  Structures
should be defined as
\begin{vsetoff}  \begin{verbatim}
typedef struct NAME {
    ...
} NAME;
\end{verbatim} \end{vsetoff}
Definitions should be grouped functionally.

It is recommended that the \NAME{struct}{} and \NAME{typedef}{} name be the
same to simplify forward references (in linked lists):
\begin{vsetoff}  \begin{verbatim}
typedef struct LISP_LIST {
    struct LISP_LIST *car;
    struct LISP_LIST *cdr;
} LISP_LIST;
\end{verbatim} \end{vsetoff}
Other references to this structure may use the \NAME{typedef} name:
\begin{vsetoff}  \begin{verbatim}
    register LISP_LIST *head;
\end{verbatim} \end{vsetoff}

\item[\underline{Global data definitions}] are next.
The suggested order is
\begin{enumerate}
\item Global variables defined in this file.
\item Static (file global) variables.
\item External variables and functions that are used throughout the
file.
\item Forward references to \NAME{static}{} functions in this file.
\end{enumerate}

If a program is large enough to require multiple source files, all
global data should be defined by a \verb'data.c' file which only
contains data definitions, while all other source files contain
\NAME{extern}{} references.  Alternatively, the file containing the main
program, documentation, and build instructions should contain data
allocation.

A very large program would contain global references in an
\verb'extern.h' \verb'#include' file in addition to a \verb'data.c'
definition file.

\item[\underline{Functions}] come last.  If the file is a main program,
the \verb'main()' function is first.
\end{description}

\subsection{Header Files}

Header files are included in other files during compilation.  Some, such
as \verb'stdio.h' are defined system-wide, and must be included by any C
programs that use the standard I/O library.  Others are used within a
single program or group of programs.

Header files should be functionally organized.  Declarations for
separate sub-systems should be in separate header files.

Header files should not be nested.  This is not permitted by Decus C and
some data objects, such as \NAME{typedef}{} and initialized data
definitions, must not be seen twice by the compiler in one compilation.

Header files should contain all \verb'#define', \NAME{typedef}, and
\NAME{extern}{} declarations necessary for a given program and shared
among two or more of its files.

Header files should not declare (i.e., allocate) variables or contain
code.  This is frequently a symptom of poor partitioning of code between
files.  One header organization that has worked well for several
medium-sized projects is:
\begin{itemize}

\item Definitions, including common data structures, are placed in one
header file. Things defined in this file are common to the entire
package.
\item All external (global) data is defined in a second header file.
\item A separate {\tt data.c} file contains all global data allocations.
\item Definitions required by bounded sub-systems are in separate header
and data allocation files.
\end{itemize}

\SECT{Declarations and Definitions}

The use of the \verb'#define' preprocessor command is especially
recommended. In general, numerical constants and array boundaries should
never be coded directly.  They should be assigned a meaningful name and
assigned their permanent value by the \verb'#define'.  This makes it
much easier to administer large and evolving programs as the constant
value can be changed uniformly by changing the \verb'#define' and
recompiling.

The enumeration data type (not in Decus C) offers an improved manner of
managing constant definitions as additional type checking is then
available.

In general, all constant values which are not strictly numeric should be
specified by \verb'#define' statements.  Exceptions to this rule are the values
0 and 1 when used as the lower boundary of an array; relative indices (if
\verb'p' is a pointer to an array element, \verb'p[1]' is the next element,
while \verb'p[-1]' is the previous element); and strictly numeric quantities.
\verb'#define' statements may even be useful in the latter situation as well: 
\begin{vsetoff}  \begin{verbatim}
#define SPEED_LIMIT    55
\end{verbatim} \end{vsetoff}
Note that defined quantities should generally be in upper-case.

Directly-coded numerical constants must have a comment explaining the
derivation of the value.

It is generally poor practice to use \verb'#define' statements to modify C syntax.
for example, the following definitions are not recommended:
\begin{vsetoff}  \begin{verbatim}
#define reg    register
#define begin  {
#define end    }
\end{verbatim} \end{vsetoff}
In certain circumstances, however, this may be necessary for proper compilation
or fastest possible execution:
\begin{vsetoff}  \begin{verbatim}
#define DIV_2  >> 1
#define DIV_4  >> 2
\end{verbatim} \end{vsetoff}
Replacing divides by right-shifts cannot be done by the compiler as it
would yield incorrect results if the divisor were negative.  If the
programmer knows that the divisor must be positive (which fact being
duly documented), this optimization becomes possible.  It should be
noted that, on some architectures such as the Intel 80186, the divide is
actually faster than the shift.  Thus, the proper format of the above
may well be:
\begin{vsetoff}  \begin{verbatim}
#ifdef i80186
#define DIV_2  / 2
#define DIV_4  / 4
#else
#define DIV_2  >> 1
#define DIV_4  >> 2
#endif
\end{verbatim} \end{vsetoff}

Also, the programmer may need to conceal non-portable quirks by means
of centrally-placed definitions:
\begin{vsetoff}  \begin{verbatim}
#ifdef decus
#define UNSIGNED_LONG  long
#else
#define UNSIGNED_LONG  unsigned long
#endif
\end{verbatim} \end{vsetoff}
As will be noted under portability, most C compilers predefine a small
number of variables that may be used to conditionally compile machine
or operating-system specific code.  This allows one program run on
multiple systems without hand-editing.

It is highly recommended that you use the following definitions freely
and consistantly:
\begin{vsetoff}  \begin{verbatim}
#define EOS    '\0'
#define FALSE  0
#define TRUE   1
#define NULLST ((char *) 0)
\end{verbatim} \end{vsetoff}
\verb'NULL' is defined by \verb'<stdio.h>' and should not be explicitly
defined by your program since some compilers require \verb'NULL' to
be type-cast.  Since \verb'NULL' is defined as a \verb'FILE *'
pointer, it should not be used to used to test references to
other objects. 

\verb'EOS' marks the end of a C string, while \verb'FALSE' and
\verb'TRUE' are used for Boolean testing.  You will probably get in the
habit of only referring to zero (or \verb'FALSE') in your \NAME{if}{}
statements:
\begin{vsetoff}  \begin{verbatim}
    if (test != 0) ...
\end{verbatim} \end{vsetoff} 

This generates the best possible code.  {\tt TRUE} is usually used to
return a ``success'' value from a function.  Don't use both {\tt TRUE}
and the integer value one in the same program to mean the same thing.
Also, even though C logical comparisons generate the values zero and
one, you should seldom use these values numerically: 
\begin{vsetoff}  \begin{verbatim}
    result = vector[a == b];
\end{verbatim} \end{vsetoff}
Instead of the above, you should be able to use the sequence
\begin{vsetoff}  \begin{verbatim}
    result = vector[(a == b) ? 1 : 0];
\end{verbatim} \end{vsetoff}
without execution-time penalty.

If a structure contains a data element that can take on one of several
values, it may be useful to put the \verb'#define' statements for each
element within the structure definition.  For example, here is a
fragment (slightly reorganized to fit on the documentation page) from a
VaxC header file that defines a VMS system structure: 
\begin{vsetoff}  \begin{verbatim}
/*
* XABSUM--Summary Extended Attribute Block
*/

struct XABSUM {
    char        xab$b_cod;
#define   XAB$C_SUM     22      /* type code    */
    char        xab$b_bln;
#define   XAB$C_SUMLEN  0x0C    /* block length */
#define   XAB$K_SUMLEN  0x0C
    ....
\end{verbatim} \end{vsetoff}

Note that the information that would be placed in each field is
\verb'#define''d following that field.  The definitions and structure
fields follow standard VMS syntax conventions.

The empty initializer \verb'{}' should never be used. Initialized
structures should be fully delimited with braces.  Constants used to
initialize longs should be explicitly long.

In any file which is part of a larger context, all local information
should be identified by use of the \NAME{static}{} keyword.  Variables, in
particular, should not be accessable outside the file unless there is an
overriding need for global access.  If these variables are shared by
only one or two other files, you should name these files in a comment.

The \NAME{readonly} specifier, available in VaxC, should be used to
signal data that does not change during execution.  On other compilers,
it may be ``hidden'' by
\begin{vsetoff}  \begin{verbatim}
    #define readonly
\end{verbatim} \end{vsetoff}

\SECT{Comments}

The importance of comments cannot be overemphasized.  In any
professional environment, many people will have to read your code,
trying to understand what you have done.  Sometimes, they wish to modify
it to do other things; sometimes they need to modify it to do what you
originally intended to do.  Consider the Programmer's Golden Rule: ``if
you make life easy for others, maybe someone will be nice to you
someday.''

The purpose of a comment is to describe your intention.  If properly
written, the code itself will adequately tell what you actually did.
There are two general types of comments:

Block comments are narratives describing the purpose of a portion of the
program text.  They are written in the following format:
\begin{vsetoff}  \begin{verbatim}
    /*
     * The comment text is written
     * here in complete sentences.
     */
\end{verbatim} \end{vsetoff}
The comment text should be at the same level of indentation as the
source code it discusses.  You should never write a comment that could
be interpreted as a C statement (unless the comment is blocking out
temporary debugging code).  A block comment should always be included at
the beginning of a major segment of the program.

Very short comments may appear on the same line as the code they
describe.  They should be tabbed over far enough to separate them from
the statements.  if more than one short comment appears in a block of
code, they should all start at the same tab position:
\begin{vsetoff}  \begin{verbatim}
    while (!finish()) {         /* Main sequence:       */
        inquire();              /* Get user request     */
        process();              /* And carry it out     */
    }                           /* As long as possible. */
\end{verbatim} \end{vsetoff}

Note that all single-line comments start at some specific column and end
with the closing \verb'*/' tabbed to column 72 on the line.  Closing
the comment at the right-hand margin makes it more readable than if the
\verb'*/' were next to the comment text itself:
\begin{vsetoff}  \begin{verbatim}
    while (!finish()) { /* Main sequence: */
        inquire(); /* Get user request */
        process(); /* And carry it out */
    } /* As long as possible. */
\end{verbatim} \end{vsetoff}
In general, you should use one-line comments to document variable
definitions and block comments to describe the computation processes.
The above comments should actually have been written as a block comment:
\begin{vsetoff}  \begin{verbatim}
    /*
     * Main sequence: get and process
     * all user requests.
     */
    while (!finish()) {
        inquire();
        process();
    }
\end{verbatim} \end{vsetoff}

\SECT{Function Declarations}

Each function should be defined beginning in column 1 (to simplify
searches for the function's definition).  If the function returns a
value or is static, that should be alone on the preceeding line.

Each formal parameter should be declared, with a comment, on a separate
line.  If the function uses any external variables or functions (that do
not return integers), these should be declared with other local
variables.  This is particularly beneficial to someone reading code
written by another.

The format for the function declaration may be illustrated as follows:
\begin{vsetoff}  \begin{verbatim}
char *
savest(string)
char    *string;        /* String to save       */
/*
 * Savest saves its argument string in free storage,
 * returning a pointer to the allocated datum.
 * It returns NULL if the allocation fails.
 */
{
    register char *ptr;
    extern char *malloc();
    extern char *strcpy();

    ptr = malloc(strlen(string) + sizeof (char));
    if (ptr != NULL)
        strcpy(ptr, string);
    return (ptr);
}
\end{verbatim} \end{vsetoff}
Note that, in the example above, the function description followed the
formal definition itself.  Another acceptable style preceeds the
function by a block comment.
\begin{vsetoff}  \begin{verbatim}
/*
 * match(string, pattern)
 *
 * If the pattern is an initial substring of string,
 * return a pointer to the first character of the
 * string beyond those matching the pattern,
 * Otherwise, return NULL.  Thus:
 *     match("abcde", "abc")
 * returns a pointer to the 'd' in the first string;
 *     match("abcde", "bc")
 * returns NULL.
 */

char *
match(string, pattern)
register char   *string;        /* Source       */
register char   *pattern;       /* for match    */
{
    while (*string == *pattern && *string != EOS) {
        pattern++;
        string++;
    }
    return ((*pattern == EOS) ? string : NULL);
}
\end{verbatim} \end{vsetoff}
In this format, the block comment is separated from the function
definition by a blank line.

The above program fragments illustrate several transportability
and maintainability issues:
\begin{itemize}

\item Although the value returned by \verb'strcpy()' is not used by the
\verb'savest()' function, it is declared so the compiler knows how to allocate
and deallocate space for the value it does return.  This is important
for compilers running on stack machines with 16-bit integers and 32-bit
character pointers.

\item On some machines, \NAME{sizeof (char)}{} is \underline{\bf not} 1.
If you want to allocate space to hold the {\tt EOS} at the end of a
string, you should use the transportable format, not the absolute value.

\item In the \verb'match()' function, note that the end of string test is
written explicitly.  You should not assume that strings are terminated
by a zero-valued byte.
\end{itemize}

\SECT{Structure and Variable Declarations}

Structures are one of the most important features of C.  They enhance
the logical organization of your code, offer consistant addressing, and
will generally increase the efficiency and performance of your programs
by a significant amount.

In general, if there are two or more ``things'' in your program that are
addressed by the same index, they should be defined by a common
structure.  This gives you great freedom to allow the program to evolve
(by adding another ``thing'' to the structure, for example), or to
modify storage allocation (from pre-compiled to dynamic allocation).

For example, if your program processes symbols--where each symbol
has a name, type, flags, and an associated value, you shouldn't
define separate vectors:
\begin{vsetoff}  \begin{verbatim}
char *name[NSYMB];
int  type[NSYMB];
int  flags[NSYMB];
int  value[NSYMB];
\end{verbatim} \end{vsetoff}
but, rather,
\begin{vsetoff}  \begin{verbatim}
typedef struct SYMBOL {
    char *sy_name;
    int  sy_type;
    int  sy_flags;
    int  sy_value;
} SYMBOL;

SYMBOL symboltable[NSYMB];
\end{verbatim} \end{vsetoff}
All structures should be defined by \NAME{typedef}{} statements.  Note,
also, the use of a header ``\verb'sy_''' to identify members of the
{\tt SYMBOL} structure. 

There is one important exception to the rule that conforming data areas
are declared by a single data structure:  the case where some data is
read-only and some read-write.  In this case, you may wish to allocate
separate areas to permit use of the \NAME{readonly}{} specifier or to
allocate read-only data in an overlay segment.

The local variables used by a function should have names that do not
duplicate global names.
\SECT{Compound Statements}

Compound statements carry out the calculations required by the C
program. They are lists of statements enclosed in braces.  They should
be tabbed over one more than the tab position of the compound statement
introducer itself.  (Four space indentation is recommended, although it
is certainly more convenient to use the hardware-provided eight position
tab stops.  If you change your mind in the middle of a program, you
should have the courtesy to re-edit the rest of the file so it is
consistant.)

The opening left brace should be at the end of the line beginning the
compound statement and the closing right brace should be alone on a
line, tabbed under the beginning of the compound statement.  Note that
the left brace beginning a function body is the only occurrance of a
left brace which is alone on a line.  This is the ``Indian Hill'' style,
also used in Kernighan \& Ritchie's book.  (Other style sheets
recommend placing the opening left brace alone on the line following the
statement opener.  Choose one style; be consistant.  This subject will
be discussed further in a subsequent section.)

The right brace before the while of a do-while statement is
the only place where a closing right brace is not alone on a line:
\begin{vsetoff}  \begin{verbatim}
    do {
        stuff();
    } while (cond != FALSE);
\end{verbatim} \end{vsetoff}
It often is good practice always to provide braces, even when they are
are not required by the language:
\begin{vsetoff}  \begin{verbatim}
    if (abc < def) {
        lesser();
    }
    else if (abc == def) {
        equal();
    }
    else {
        greater();
    }
\end{verbatim} \end{vsetoff}
This prevents suprises when you add debugging statements.

Never, never, write nested conditionals or loops without braces:
\begin{vsetoff}  \begin{verbatim}
    for (dp = &values[0]; dp < top_value; dp++)
        if (dp->d_value == arg_value
         && (dp->d_flag & arg_flag) != 0)
            return (dp);
    return (NULL);
\end{verbatim} \end{vsetoff}
While the above is correct C; it is unmaintainable and should always be
written as
\begin{vsetoff}  \begin{verbatim}
    for (dp = &values[0]; dp < top_value; dp++) {
        if (dp->d_value == arg_value
         && (dp->d_flag & arg_flag) != 0) {
             return (dp);
        }
    }
    return (NULL);
\end{verbatim} \end{vsetoff}

If the span of a block is large (more than about 40 lines) or there are
several nested blocks, closing braces should be commented to indicate
what part of the process they delimit:
\begin{vsetoff}  \begin{verbatim}
    for (sy = sytable; sy != NULL; sy = sy->sy_link) {
        if (sy->sy_flag == DEFINED) {
            ...
        }                /* if defined                  */
        else {
            ...
        }               /* if undefined                 */
    }                   /* for all symbols              */
\end{verbatim} \end{vsetoff}

Each line should contain one and only one statement.  The only exception
to this is the \NAME{else if}{} construction as shown above. In a sequence
of \NAME{if}{} ... \NAME{else}{} statements, there should always be a
terminating \NAME{else}{} even if it is merely a dummy statement. Note
especially that an \NAME{if}{} statement and its associated conditionally
executed statement appear on separate lines.

If a \NAME{for}, \NAME{if}, or \NAME{while}{} statement has a dummy body,
the semicolon must go on the next line:
\begin{vsetoff}  \begin{verbatim}
    /*
     * Locate end of string
     */
    for (charp = string; *charp != EOS; charp++)
        ;
\end{verbatim} \end{vsetoff}

There are few more insidious bugs than an extra semicolon tacked on the
end of a \NAME{for}{} or \NAME{if}{} statement. Everything will compile
normally and the code might even work for some cases, but--because of
the invisibility of the semicolon--the bug will be very difficult to
track down.

There should always be a blank between reserved words and their opening
parentheses, e.g., \NAME{if (condition)}{} rather than
\NAME{if(condition)}. There should also be parentheses around the
objects of \NAME{sizeof}{} and \NAME{return}.

If the conditional test in an \NAME{if}{} statement is so complex that it
requires more than one line, break it at an \verb'&&' or \verb'||', and
line up the expressions so the tests line up as well:
\begin{vsetoff}  \begin{verbatim}
    if (a == b
     && b == c) {
        printf("a == c");
    }
\end{verbatim} \end{vsetoff}
If the conditional test extends over one line, always enclose the
conditionally-executed statement in braces.

The above is a special case of a more general recommendation that you
break statements across lines at meaningful boundaries, and attempt to
align the components to make the meaning clear.  For example, the
following sequence computes the length of an RMS logical record.
\begin{vsetoff}  \begin{verbatim}
    r->lrecl = r->rab.rab$w_rsz /* Record size from RAB */
     + ((hbyte != EOS) ? 1 : 0) /* If header byte       */
     + ((tbyte != EOS) ? 1 : 0) /* If trailer byte      */
     - offset                   /* For Fortran hacking  */
     + hnewline                 /* For VFC hacking      */
     + tnewline;                /* For VFC hacking      */
\end{verbatim} \end{vsetoff}

Switch statements offer a good alternative to multiple
\NAME{if}...\NAME{else}{} sequences.  Each case appears by itself on a
line, tabbed under the switch itself.  The \NAME{break}{} that terminates
a case should be followed by a blank line. The ``fall through'' feature
of C's \NAME{switch}{} statement should rarely, if ever, be used.  If it
is needed, it must be commented for further reference:
\begin{vsetoff}  \begin{verbatim}
    eow = 0;
    while ((c = getchar()) != EOF) {
        switch (c) {
        case '\n':      /* Newline,                     */
            lines++;    /* count lines                  */
            /*
             * Fall through to "end of word" case
             */
        case '\t':      /* Tabs, newlines, and blanks   */
        case ' ':       /* Form words.                  */
            words += eow;
            eow = 0;    /* Don't count multiple runs    */
            letters++;  /* But count all "whitespace"   */
            break;

        default:        /* All the rest form a word      */
            letters++;
            eow = 1;
            break;
        }
    }
    words += eow;        /* Fix count of last word       */
\end{verbatim} \end{vsetoff}
The above implements the central algorithm of a ``word count'' routine
where a newline, blank, or tab terminates a word, but multiple blanks do
not increase the number of words.

Note that the \NAME{break}{} following the last case is redundant, but
should be provided to make the programmer's intent clear.  In general,
the \NAME{default}{} case should be last.

All \NAME{switch}{} statements should have a default case, which may
merely be a ``fatal error'' exit.

\SECT{Expressions and Operators} C
is an expression language.  This means--in essence--that the assignment
statement ``\verb'a = b''' itself has a value which can be embedded in a
larger context.  This should be used very sparingly.  For example,
\begin{vsetoff}  \begin{verbatim}
    while ((value = *pointer++) != 0) {
        process(value);
    }
\end{verbatim} \end{vsetoff}
shows a standard C idiom which all programmers should recognize.  It
is essential, however, that you do not carry this to extremes by embedding
mutiple assignments (or other side-effects) in a statement.

Blanks should surround all binary operators except those which compose
primaries, (\verb'., ->').  No blanks should separate a unary
operator (such as \verb'-, &, [], !') from its operand.
\NAME{sizeof}{} and \NAME{return}{} are exceptions to this rule.

Some judgement is called for here as there are a few situations when
complex expressions become clearer when inner constructions don't have
spaces.  For example,
\begin{vsetoff}  \begin{verbatim}
    x = (a*b) + (c*d);
\end{verbatim} \end{vsetoff}

Blanks should appear after commas in argument lists to help separate the
arguments visually.  On the other hand, macros with arguments and
function calls should not have a blank between the name and the left
parenthesis.

Side effects within expressions should be used sparingly.  No more than
one operator with a side-effect (\verb'=, op=, ++, --') should appear
within an expression.  It is very easy to misunderstand the rules for C
compilation and get side-effects compiled in the wrong order.  For
example,
\begin{vsetoff}  \begin{verbatim}
    func(*ptr++, *ptr++);
    *ptr = *ptr++;
    *ptr++ = *ptr;
\end{verbatim} \end{vsetoff}

Are not necessarily going to do what you expect; and {\it are} going to
do different things on different implementations of C.

The old versions of the assigned operators (\verb'=+', etc.) must
not be used. Always surround assigned operators by spaces.
``\verb'x=*foo''' is interpreted as ``\verb'x = x * foo''' (even if foo
is a pointer) by some compilers.

The comma operator should be used exceedingly sparingly.  One of the
few appropriate places is in a for statement:
\begin{vsetoff}  \begin{verbatim}
    for (sum = 0, ptr = &array[0]; ptr < &array[A_MAX];) {
        sum += *ptr++;
    }
\end{verbatim} \end{vsetoff}

Since C has some unexpected operator precedence rules, all expressions
involving mixed operators should be fully parenthesized.  This is
especially true when comparison or mask operators (\verb'&', \verb'|',
and \verb'^') are combined with shifts.  Always write
\begin{vsetoff}  \begin{verbatim}
    if (value > (1 << 12))
        ...
\end{verbatim} \end{vsetoff}
with parentheses around the shift operation.

\SECT{Naming Things}

When a program must be used as part of a larger context, whether it be a
subroutine library, or an independent program within an application
package, the programmer's creativity in defining mnemonic names must be
subservient to the needs of the group as a whole.

\subsection{Naming Rules}
\begin{itemize}
\item Application program names should follow a standard format, such as:
\begin{itemize}
\item The 1st 2 or 3 characters = sub-system code
\item The rest = unique meaningful identifier
\end{itemize}

\item Names (variables; \NAME{struct}{} and \NAME{union}{} declarations; and
procedures) are written lower-case, unique in the first eight
characters.  (Some C systems require names to be unique in the first six
characters.) 

External names must be unique in the first six characters and may not
use alphabetic case to distinguish variables. 

If the first letter in an external name is an underscore \verb'_' it
indicates a Unix system-internal name, (such as a routine within a
file-management I/O system). Application programs should not use this as
it implies system-level programming.  Trailing underscores should also
be avoided. 

(Note that any use of underscore may conflict with variables defined by
your operating systems.  For example, on RSX-11M, the operating system
file management routines use--in effect--a leading underscore.)

Longer names and underscore should be used freely to improve readability
and understandability.

Upper-case and lower-case should not be mixed in a name.

Names more than four characters long should differ by at least two characters:
\begin{vsetoff}  \begin{verbatim}
int systst, sysstst;        /* are easily confused  */
\end{verbatim} \end{vsetoff}

Constants (things named by a \verb'#define') should be in all upper-case.

All names must be unique, ignoring case. In other words, even though C
knows that {\tt this} is different from {\tt THIS}, do not do it.

Although this guide recommends keeping variables in lowercase only, and
\verb'#define''d constants in uppercase only, there are a few times when
breaking this rule results in greater clarity. It is better to be
compatible with an externally-defined standard, even if it is in mixed
case.  For example, if the hardware documentation for a chip refers to
\verb'TxRdy', your device driver should use the same format to refer to
this entity.
\end{itemize}

