logo_kerberos.gif

Coding style/Formatting

From K5Wiki
< Coding style
Revision as of 06:55, 6 May 2008 by TomYu (talk | contribs) (continuation lines)

Jump to: navigation, search

The following coding style considerations apply to the most mechanical aspects of C source code style.

Maximum width 79 columns

Source code lines should not exceed 79 columns in width.

Current conformance

Existing code mostly conforms to this guideline.

Rationale

A width of 79 columns fits on most terminals, and is most suitable for printing with a decent column width. Long lines resulting from deeply indented code are often a symptom of design flaws.

Four-column basic indentation offset

Every level of block nesting should be indented by an additional four columns. Labels, including "switch" labels, should be at one less level of indentation than their surrounding code:

void
foo(int x)
{
    switch (x) {
    case 0:
        bar();
        break;
    case 1:
        quux();
        break;
    default:
        break;
    }
}

[needs more detail]

Current conformance

Existing code varies in conformance. Much of the core library code (src/lib/krb5, etc.) conforms, but other subsystems chose different indentation offsets. Exceptions include:

  • Code of BSD-related origin -- typically eight columns
    • src/plugins/kdb/db2/libdb2
    • src/lib/rpc
    • Parts of src/lib/gssapi/mechglue
  • Code derived from OpenVision -- various
    • Parts of src/lib/gssapi/krb5
    • src/lib/kadm5
    • src/kadmin

Rationale

Combined with the 79-column width limit, this somewhat limits the level of nesting. This indentation offset allows for visual identification of indentation levels while avoiding long-line problems resulting from using an eight-column indentation offset with some of the long identifier names we use.

No tab characters

No tab characters should appear in source files. This guideline will probably be one of the more difficult ones to adopt in a non-disruptive manner.

Current conformance

Existing code does not conform. Much of the existing code was written in Emacs, which defaults to using sequential tab characters at the beginning of stretches of horizontal whitespace longer than one column.

Rationale

Tab stop locations are not consistent across different editors and platforms, and can make code harder to read on a platform other than the one on which it was written. Tab characters also make diffs harder to read.

No trailing whitespace

There should be no whitespace at the end of a line. Blank lines should not contain any horizontal whitespace.

Current conformance

Existing code is highly variable in this area. Particularly problematic are boilerplate, such as copyright notices, which contain trailing whitespace. Blank lines in code sometimes contain indentation whitespace.

Rationale

Trailing whitespace is difficult to see in many editors. It can also create problems when generating patch files.

Comment formatting

Comments to the right of code start in column 32. Comments not to the right of code are indented at the prevailing indent for the surrounding code. Make the comments complete sentences. If you need more than one line, make them into block comments, like this:

/*
 * This is a block comment.  It should consist of complete
 * sentences.
 *
 * Paragraphs should be separated by blank lines so that emacs
 * fill commands will work properly.
 */

Really important single-line comments should also be done in block form:

/*
 * This is a really important one-line comment.
 */

In order to get the start and end delimiters for block comments to stay when you use emacs to fill paragraphs in the comments, set both the c-hanging-comment-starter-p and the c-hanging-comment-ender-p variables to nil. This will be done by the tentative "krb5" style for the emacs cc-mode.

Since we are mostly aiming for C '89 compatibility, don't use "//" comments.

For Doxygen markup in comment blocks, use "!" (exclamation point) to begin a Doxygen block, and "\" (backslash) for Doxygen command keywords.

/*!
 * \file krb5.h
 * \brief the main krb5 header
 */

Current conformance

Rationale

Horizontal white space

One space goes after keywords ("if", "for", "while", "for", "do", "switch", and "return"). Do not put a space after "sizeof", but do parenthesize its argument. Do not put a space between a function name and the opening parenthesis of its argument list. Do not put a space after a cast operator. Do not put a space between a keyword and its immediately-following semicolon. One space goes after each comma in a function argument or parameter list or comma expression.

if (x) {
    foo((long)x);
}
while (y) {
    baz(&y);
    if (quux())
        return;
}

Semicolons separating the expressions of a "for" statement have one space after them unless the following expression is empty.

for (;;) {
    /* ... */
}

for (i = 0; i < n; i++) {
    /* ... */
}

Put spaces around binary operators, but not around unary or postfix operators. The structure member operators "." and "->" count as postfix operators, not binary operators.

x = --a + b / c - d++;
y = p->z.v[x];

Omitting spaces around some binary operators may be justified when it improves readability:

s[len+1] = '\0';

Put spaces around the "?" and ":" characters in a conditional expression:

x = y ? f() : g();

Current conformance

Spacing around binary operators is mostly consistent. Existing code is not consistent about putting the opening parenthesis of a function call immediately after the function name.

Rationale

Extra spacing around keywords helps to distinguish them from functions. Spacing around binary operators improves readability. Some of the arbitrary quirks in these guidelines ("sizeof", cast operators) are for consistency with BSD coding style.

Continuation lines

When breaking long lines, the continuation lines should be indented by an additional indentation level. Break lines after binary operators, not before. When continuing a parenthesized expression, line up the continuation to the right of the corresponding opening parenthesis.

x = y + z + do_something_here() * number_of_the_counting +
    do_something_else() + quux;
if (x != y && silly_variable <= something_long_here &&
    random_comparision(x, y) == 0) {
    /* ... */
}

Current conformance

Existing code varies.

Rationale

This guideline is mostly for consistency with BSD style, except that BSD style uses half-indents for continuations.

Function definitions and declarations

Function names in function definitions should begin at the leftmost column. The return type name of a function in a function definition should go on the line preceding the function name. The opening brace of a function definition should also go in the leftmost column. Use ANSI-style function definitions, not the K&R style; the K&R style is obsolescent.

char *
foo(int a)
{
    /* ... */
}

For functions with sufficiently many arguments that they do not fit on one line, one possibility is to place one parameter per line like:

krb5_error_code
krb5_do_something(
    krb5_context context,
    char *string)
{
    /* ... */
}

Note that the opening parenthesis is at the end of the line, and the closing parenthesis immediately follows the final parameter.

Another style is to line up the continuation of the parameter list to the right of the opening parenthesis:

int
lengthy_function_name(char *really, int ridiculously, long lengthy_argument,
                      void *list, struct goes *here)
{
    /* ... */
}

Try to use a consistent form within a file.

For function prototype declarations that are not part of a definition, do not omit parameter names, and try to place the return type name on the same line as the function name. Also, try to avoid the above one-line-per-parameter style for prototypes. Some function prototypes will have many characters preceding the function name, such as calling convention or other attribute macros; when combined with a long function name, this makes putting the function name at the beginning of a line a better idea:

krb5_error_code KRB5_CALLCONV
krb5_calculate_checksum(krb5_context context, krb5_cksumtype ctype,
                        krb5_const_pointer in, size_t in_length,
                        krb5_const_pointer seed, size_t seed_length,
                        krb5_checksum *outcksum);

Current conformance

Existing code is variable.

Rationale

Placing function names in the leftmost column helps some tools, such as ctags or Emacs.

Omitting parameter names from prototypes is the usual style for system headers, as an attempt to minimize namespace conflicts. (Parameter name identifiers in function prototype declarations have a scope ending with the closing parenthesis of the prototype, and should be irrelevant, but user-defined macros can rewrite the parameter names, causing syntax errors or unintended effects.) Leaving parameter names in prototypes helps a reader remember the meanings of the parameters. Alternatives, such as putting a parameter name in a comment, are less readable to humans and to Doxygen. (Doxygen also does not handle omitted parameter names.)

Flow control statements

Braces opening substatements, such as those following "if", "else", "while", "for", "do", and "switch" should be on the same line as the keyword or expression associated with that substatement. There should be one space before the opening brace. This is sometimes called "hanging" braces. The closing brace of the substatement should be the first non-whitespace character on its line, and be placed at the same indentation level as the keyword for that substatement.

if (x) {
    foo(x);
}

The "while" keyword in a do-while construct should sit on the same line as the closing brace of the substatement following "do":

do {
    baz();
} while (x);

An "if" substatement immediately following an "else" keyword should be on the same line as the "else":

if (x) {
    foo();
} else if (y) {
    bar();
}

Do not parenthesize the expression in a "return" statement.

Current conformance

Existing code mostly conforms. Some Sun-derived code parenthesizes the expressions of "return" statements.

Rationale

This style is mostly for consistency with the BSD coding style. The GNU brace style consumes a larger amount of vertical space. The "brace-else-if-brace" style also prevents "stairstepping" within a long series of conditional statements.