Previous Page
Next Page

1.4. Comments

You should use comments generously in the source code to document your C programs. There are two ways to insert a comment in C: block comments begin with /* and end with */, and line comments begin with // and end with the next new line character.

You can use the /* and */ delimiters to begin and end comments within a line, and to enclose comments of several lines. For example, in the following function prototype, the ellipsis (...) signifies that the open( ) function has a third, optional parameter. The comment explains the usage of the optional parameter:

    int open( const char *name, int mode, ... /* int permissions */ );

You can use // to insert comments that fill an entire line, or to write source code in a two-column format, with program code on the left and comments on the right:

    const double pi = 3.1415926536;     // Pi is constant

These line comments were officially added to the C language by the C99 standard, but most compilers already supported them even before C99. They are sometimes called "C++-style" comments, although they originated in C's forerunner, BCPL.

Inside the quotation marks that delimit a character constant or a string literal, the characters /* and // do not start a comment. For example, the following statement contains no comments:

    printf( "Comments in C begin with /* or //.\n" );

The only thing that the preprocessor looks for in examining the characters in a comment is the end of the comment; thus it is not possible to nest block comments. However, you can insert /* and */ to comment out part of a program that contains line comments:

    /* Temporarily removing two lines:
      const double pi = 3.1415926536;     // Pi is constant
      area = pi * r * r                   // Calculate the area
       Temporarily removed up to here */

If you want to comment out part of a program that contains block comments, you can use a conditional preprocessor directive (described in Chapter 14):

    #if 0
      const double pi = 3.1415926536;     /* Pi is constant     */
      area = pi * r * r                   /* Calculate the area */
    #endif

The preprocessor replaces each comment with a space. The character sequence min/*max*/Value thus becomes the two tokens min Value.


Previous Page
Next Page