Go to the first, previous, next, last section, table of contents.

# Making The Best Use of C

This chapter provides advice on how best to use the C language when writing GNU software.

- Formatting: Formatting Your Source Code
- Comments: Commenting Your Work
- Syntactic Conventions: Clean Use of C Constructs
- Names: Naming Variables and Functions
- System Portability: Portability between different operating systems
- CPU Portability: Supporting the range of CPU types
- System Functions: Portability and "standard" library functions
- Internationalization: Techniques for internationalization
- Mmap: How you can safely use `mmap`.

## Formatting Your Source Code

It is important to put the open-brace that starts the body of a C function in column zero, and avoid putting any other open-brace or open-parenthesis or open-bracket in column zero. Several tools look for open-braces in column zero to find the beginnings of C functions. These tools will not work on code not formatted that way.

It is also important for function definitions to start the name of the function in column zero. This helps people to search for function definitions, and may also help certain tools recognize them. Thus, the proper format is this:

    static char *
    concat (s1, s2)        /* Name starts in column zero here */
         char *s1, *s2;
    {                     /* Open brace in column zero here */
      ...
    }

or, if you want to use ANSI C, format the definition like this:

    static char *
    concat (char *s1, char *s2)
    {
      ...
    }

In ANSI C, if the arguments don't fit nicely on one line, split it like this:

    int
    lots_of_args (int an_integer, long a_long, short a_short,
                  double a_double, float a_float)
    ...

For the body of the function, we prefer code formatted like this:

    if (x < foo (y, z))
      haha = bar[4] + 5;
    else
      {
        while (z)
          {
            haha += foo (z, z);
            z--;
          }
        return ++x + bar ();
      }

We find it easier to read a program when it has spaces before the open-parentheses and after the commas. Especially after the commas.

When you split an expression into multiple lines, split it before an operator, not after one. Here is the right way:

    if (foo_this_is_long && bar > win (x, y, z)
        && remaining_condition)

Try to avoid having two operators of different precedence at the same level of indentation. For example, don't write this:

    mode = (inmode[j] == VOIDmode
            || GET_MODE_SIZE (outmode[j]) > GET_MODE_SIZE (inmode[j])
            ? outmode[j] : inmode[j]);

Instead, use extra parentheses so that the indentation shows the nesting:

    mode = ((inmode[j] == VOIDmode
             || (GET_MODE_SIZE (outmode[j]) > GET_MODE_SIZE (inmode[j])))
            ? outmode[j] : inmode[j]);

Insert extra parentheses so that Emacs will indent the code properly. For example, the following indentation looks nice if you do it by hand, but Emacs would mess it up:

    v = rup->ru_utime.tv_sec*1000 + rup->ru_utime.tv_usec/1000
        + rup->ru_stime.tv_sec*1000 + rup->ru_stime.tv_usec/1000;

But adding a set of parentheses solves the problem:

    v = (rup->ru_utime.tv_sec*1000 + rup->ru_utime.tv_usec/1000
         + rup->ru_stime.tv_sec*1000 + rup->ru_stime.tv_usec/1000);

Format do-while statements like this:

    do
      {
        a = foo (a);
      }
    while (a > 0);

Please use formfeed characters (control-L) to divide the program into pages at logical places (but not within a function). It does not matter just how long the pages are, since they do not have to fit on a printed page. The formfeeds should appear alone on lines by themselves.

## Commenting Your Work

Every program should start with a comment saying briefly what it is for. Example: ``fmt - filter for simple filling of text'`.

Please write the comments in a GNU program in English, because English is the one language that nearly all programmers in all countries can read. If you do not write English well, please write comments in English as well as you can, then ask other people to help rewrite them. If you can't write comments in English, please find someone to work with you and translate your comments into English.

Please put a comment on each function saying what the function does, what sorts of arguments it gets, and what the possible values of arguments mean and are used for. It is not necessary to duplicate in words the meaning of the C argument declarations, if a C type is being used in its customary fashion. If there is anything nonstandard about its use (such as an argument of type `char *` which is really the address of the second character of a string, not the first), or any possible values that would not work the way one would expect (such as, that strings containing newlines are not guaranteed to work), be sure to say so.

Also explain the significance of the return value, if there is one.

Please put two spaces after the end of a sentence in your comments, so that the Emacs sentence commands will work. Also, please write complete sentences and capitalize the first word. If a lower-case identifier comes at the beginning of a sentence, don't capitalize it! Changing the spelling makes it a different identifier. If you don't like starting a sentence with a lower case letter, write the sentence differently (e.g., "The identifier lower-case is ...").

The comment on a function is much clearer if you use the argument names to speak about the argument values. The variable name itself should be lower case, but write it in upper case when you are speaking about the value rather than the variable itself. Thus, "the inode number NODE_NUM" rather than "an inode".

There is usually no purpose in restating the name of the function in the comment before it, because the reader can see that for himself. There might be an exception when the comment is so long that the function itself would be off the bottom of the screen.

There should be a comment on each static variable as well, like this:

    /* Nonzero means truncate lines in the display;
       zero means continue them.  */
    int truncate_lines;

Every ``#endif'` should have a comment, except in the case of short conditionals (just a few lines) that are not nested. The comment should state the condition of the conditional that is ending, including its sense. ``#else'` should have a comment describing the condition and sense of the code that follows. For example:

    #ifdef foo
      ...
    #else /* not foo */
      ...
    #endif /* not foo */

but, by contrast, write the comments this way for a ``#ifndef'`:

    #ifndef foo
      ...
    #else /* foo */
      ...
    #endif /* foo */

## Clean Use of C Constructs

Please explicitly declare all arguments to functions. Don't omit them just because they are `int`s.

Declarations of external functions and functions to appear later in the source file should all go in one place near the beginning of the file (somewhere before the first function definition in the file), or else should go in a header file. Don't put `extern` declarations inside functions.

It used to be common practice to use the same local variables (with names like `tem`) over and over for different values within one function. Instead of doing this, it is better declare a separate local variable for each distinct purpose, and give it a name which is meaningful. This not only makes programs easier to understand, it also facilitates optimization by good compilers. You can also move the declaration of each local variable into the smallest scope that includes all its uses. This makes the program even cleaner.

Don't use local variables or parameters that shadow global identifiers.

Don't declare multiple variables in one declaration that spans lines. Start a new declaration on each line, instead. For example, instead of this:

    int    foo,
           bar;

write either this:

    int foo, bar;

or this:

    int foo;
    int bar;

(If they are global variables, each should have a comment preceding it anyway.)

When you have an `if`-`else` statement nested in another `if` statement, always put braces around the `if`-`else`. Thus, never write like this:

    if (foo)
      if (bar)
        win ();
      else
        lose ();

always like this:

    if (foo)
      {
        if (bar)
          win ();
        else
          lose ();
      }

If you have an `if` statement nested inside of an `else` statement, either write `else if` on one line, like this,

    if (foo)
      ...
    else if (bar)
      ...

with its `then`-part indented like the preceding `then`-part, or write the nested `if` within braces like this:

    if (foo)
      ...
    else
      {
        if (bar)
          ...
      }

Don't declare both a structure tag and variables or typedefs in the same declaration. Instead, declare the structure tag separately and then use it to declare the variables or typedefs.

Try to avoid assignments inside `if`-conditions. For example, don't write this:

    if ((foo = (char *) malloc (sizeof *foo)) == 0)
      fatal ("virtual memory exhausted");

instead, write this:

    foo = (char *) malloc (sizeof *foo);
    if (foo == 0)
      fatal ("virtual memory exhausted");

Don't make the program ugly to placate `lint`. Please don't insert any casts to `void`. Zero without a cast is perfectly fine as a null pointer constant, except when calling a varargs function.

## Naming Variables and Functions

The names of global variables and functions in a program serve as comments of a sort. So don't choose terse names--instead, look for names that give useful information about the meaning of the variable or function. In a GNU program, names should be English, like other comments.

Local variable names can be shorter, because they are used only within one context, where (presumably) comments explain their purpose.

Please use underscores to separate words in a name, so that the Emacs word commands can be useful within them. Stick to lower case; reserve upper case for macros and `enum` constants, and for name-prefixes that follow a uniform convention.

For example, you should use names like `ignore_space_change_flag`; don't use names like `iCantReadThis`.

Variables that indicate whether command-line options have been specified should be named after the meaning of the option, not after the option-letter. A comment should state both the exact meaning of the option and its letter. For example,

    /* Ignore changes in horizontal whitespace (-b).  */
    int ignore_space_change_flag;

When you want to define names with constant integer values, use `enum` rather than ``#define'`. GDB knows about enumeration constants.

Use file names of 14 characters or less, to avoid creating gratuitous problems on older System V systems. You can use the program `doschk` to test for this. `doschk` also tests for potential name conflicts if the files were loaded onto an MS-DOS file system--something you may or may not care about.

## Portability between System Types

In the Unix world, "portability" refers to porting to different Unix versions. For a GNU program, this kind of portability is desirable, but not paramount.

The primary purpose of GNU software is to run on top of the GNU kernel, compiled with the GNU C compiler, on various types of CPU. The amount and kinds of variation among GNU systems on different CPUs will be comparable to the variation among Linux-based GNU systems or among BSD systems today. So the kinds of portability that are absolutely necessary are quite limited.

But many users do run GNU software on non-GNU Unix or Unix-like systems. So supporting a variety of Unix-like systems is desirable, although not paramount.

The easiest way to achieve portability to most Unix-like systems is to use Autoconf. It's unlikely that your program needs to know more information about the host platform than Autoconf can provide, simply because most of the programs that need such knowledge have already been written.

Avoid using the format of semi-internal data bases (e.g., directories) when there is a higher-level alternative (`readdir`).

As for systems that are not like Unix, such as MSDOS, Windows, the Macintosh, VMS, and MVS, supporting them is usually so much work that it is better if you don't.

The planned GNU kernel is not finished yet, but you can tell which facilities it will provide by looking at the GNU C Library Manual. The GNU kernel is based on Mach, so the features of Mach will also be available. However, if you use Mach features, you'll probably have trouble debugging your program today.

## Portability between CPUs

Even GNU systems will differ because of differences among CPU types--for example, difference in byte ordering and alignment requirements. It is absolutely essential to handle these differences. However, don't make any effort to cater to the possibility that an `int` will be less than 32 bits. We don't support 16-bit machines in GNU.

Don't assume that the address of an `int` object is also the address of its least-significant byte. This is false on big-endian machines. Thus, don't make the following mistake:

    int c;
    ...
    while ((c = getchar()) != EOF)
      write(file_descriptor, &c, 1);

When calling functions, you need not worry about the difference between pointers of various types, or between pointers and integers. On most machines, there's no difference anyway. As for the few machines where there is a difference, all of them support ANSI C, so you can use prototypes (conditionalized to be active only in ANSI C) to make the code work on those systems.

In certain cases, it is ok to pass integer and pointer arguments indiscriminately to the same function, and use no prototype on any system. For example, many GNU programs have error-reporting functions that pass their arguments along to `printf` and friends:

    error (s, a1, a2, a3)
         char *s;
         int a1, a2, a3;
    {
      fprintf (stderr, "error: ");
      fprintf (stderr, s, a1, a2, a3);
    }

In practice, this works on all machines, and it is much simpler than any "correct" alternative. Be sure not to use a prototype for such functions.

However, avoid casting pointers to integers unless you really need to. These assumptions really reduce portability, and in most programs they are easy to avoid. In the cases where casting pointers to integers is essential--such as, a Lisp interpreter which stores type information as well as an address in one word--it is ok to do so, but you'll have to make explicit provisions to handle different word sizes.

## Calling System Functions

C implementations differ substantially. ANSI C reduces but does not eliminate the incompatibilities; meanwhile, many users wish to compile GNU software with pre-ANSI compilers. This chapter gives recommendations for how to use the more or less standard C library functions to avoid unnecessary loss of portability.

- Don't use the value of `sprintf`. It returns the number of characters written on some systems, but not on all systems.
- `main` should be declared to return type `int`. It should terminate either by calling `exit` or by returning the integer status code; make sure it cannot ever return an undefined value.
- Don't declare system functions explicitly. Almost any declaration for a system function is wrong on some system. To minimize conflicts, leave it to the system header files to declare system functions. If the headers don't declare a function, let it remain undeclared. While it may seem unclean to use a function without declaring it, in practice this works fine for most system library functions on the systems where this really happens; thus, the disadvantage is only theoretical. By contrast, actual declarations have frequently caused actual conflicts.
- If you must declare a system function, don't specify the argument types. Use an old-style declaration, not an ANSI prototype. The more you specify about the function, the more likely a conflict.
- In particular, don't unconditionally declare `malloc` or `realloc`. Most GNU programs use those functions just once, in functions conventionally named `xmalloc` and `xrealloc`. These functions call `malloc` and `realloc`, respectively, and check the results. Because `xmalloc` and `xrealloc` are defined in your program, you can declare them in other files without any risk of type conflict. On most systems, `int` is the same length as a pointer; thus, the calls to `malloc` and `realloc` work fine. For the few exceptional systems (mostly 64-bit machines), you can use conditionalized declarations of `malloc` and `realloc`---or put these declarations in configuration files specific to those systems.
- The string functions require special treatment. Some Unix systems have a header file ``string.h'`; others have ``strings.h'`. Neither file name is portable. There are two things you can do: use Autoconf to figure out which file to include, or don't include either file.
- If you don't include either strings file, you can't get declarations for the string functions from the header file in the usual way. That causes less of a problem than you might think. The newer ANSI string functions should be avoided anyway because many systems still don't support them. The string functions you can use are these:

      strcpy   strncpy   strcat   strncat
      strlen   strcmp    strncmp
      strchr   strrchr

  The copy and concatenate functions work fine without a declaration as long as you don't use their values. Using their values without a declaration fails on systems where the width of a pointer differs from the width of `int`, and perhaps in other cases. It is trivial to avoid using their values, so do that. The compare functions and `strlen` work fine without a declaration on most systems, possibly all the ones that GNU software runs on. You may find it necessary to declare them conditionally on a few systems. The search functions must be declared to return `char *`. Luckily, there is no variation in the data type they return. But there is variation in their names. Some systems give these functions the names `index` and `rindex`; other systems use the names `strchr` and `strrchr`. Some systems support both pairs of names, but neither pair works on all systems. You should pick a single pair of names and use it throughout your program. (Nowadays, it is better to choose `strchr` and `strrchr` for new programs, since those are the standard ANSI names.) Declare both of those names as functions returning `char *`. On systems which don't support those names, define them as macros in terms of the other pair. For example, here is what to put at the beginning of your file (or in a header) if you want to use the names `strchr` and `strrchr` throughout:

      #ifndef HAVE_STRCHR
      #define strchr index
      #endif
      #ifndef HAVE_STRRCHR
      #define strrchr rindex
      #endif

      char *strchr ();
      char *strrchr ();

Here we assume that `HAVE_STRCHR` and `HAVE_STRRCHR` are macros defined in systems where the corresponding functions exist. One way to get them properly defined is to use Autoconf.

## Internationalization

GNU has a library called GNU gettext that makes it easy to translate the messages in a program into various languages. You should use this library in every program. Use English for the messages as they appear in the program, and let gettext provide the way to translate them into other languages.

Using GNU gettext involves putting a call to the `gettext` macro around each string that might need translation--like this:

    printf (gettext ("Processing file `%s'..."));

This permits GNU gettext to replace the string `"Processing file `%s'..."` with a translated version.

Once a program uses gettext, please make a point of writing calls to `gettext` when you add new strings that call for translation.

Using GNU gettext in a package involves specifying a text domain name for the package. The text domain name is used to separate the translations for this package from the translations for other packages. Normally, the text domain name should be the same as the name of the package--for example, ``fileutils'` for the GNU file utilities.

To enable gettext to work well, avoid writing code that makes assumptions about the structure of words or sentences. When you want the precise text of a sentence to vary depending on the data, use two or more alternative string constants each containing a complete sentences, rather than inserting conditionalized words or phrases into a single sentence framework.

Here is an example of what not to do:

    printf ("%d file%s processed", nfiles,
            nfiles != 1 ? "s" : "");

The problem with that example is that it assumes that plurals are made by adding `s'. If you apply gettext to the format string, like this,

    printf (gettext ("%d file%s processed"), nfiles,
            nfiles != 1 ? "s" : "");

the message can use different words, but it will still be forced to use `s' for the plural. Here is a better way:

    printf ((nfiles != 1 ? "%d files processed"
             : "%d file processed"),
            nfiles);

This way, you can apply gettext to each of the two strings independently:

    printf ((nfiles != 1 ? gettext ("%d files processed")
             : gettext ("%d file processed")),
            nfiles);

This can any method of forming the plural of the word for "file", and also handles languages that require agreement in the word for "processed".

A similar problem appears at the level of sentence structure with this code:

    printf ("#  Implicit rule search has%s been done.\n",
            f->tried_implicit ? "" : " not");

Adding `gettext` calls to this code cannot give correct results for all languages, because negation in some languages requires adding words at more than one place in the sentence. By contrast, adding `gettext` calls does the job straightfowardly if the code starts out like this:

    printf (f->tried_implicit
            ? "#  Implicit rule search has been done.\n",
            : "#  Implicit rule search has not been done.\n");

## Mmap

Don't assume that `mmap` either works on all files or fails for all files. It may work on some files and fail on others.

The proper way to use `mmap` is to try it on the specific file for which you want to use it--and if `mmap` doesn't work, fall back on doing the job in another way using `read` and `write`.

The reason this precaution is needed is that the GNU kernel (the HURD) provides a user-extensible file system, in which there can be many different kinds of "ordinary files." Many of them support `mmap`, but some do not. It is important to make programs handle all these kinds of files.

Go to the first, previous, next, last section, table of contents.