Comments

A comment is text replaced during preprocessing by a single space character; the compiler therefore ignores all comments.

There are two kinds of comments:

You can put comments anywhere the language allows white space. You cannot nest C-style comments inside other C-style comments. Each comment ends at the first occurrence of */.

You can also include multibyte characters within a comment.

Note:
The /* or */ characters found in a character constant or string literal do not start or end comments.

In the following program, the second printf() is a comment:

 #include <stdio.h>

 int main(void)
 {
    printf("This program has a comment.\n");
    /* printf("This is a comment line and will not print.\n"); */
 return 0;
 }

Because the second printf() is equivalent to a space, the output of this program is:

This program has a comment.

Because the comment delimiters are inside a string literal, printf() in the following program is not a comment.

#include <stdio.h>

    int main(void)
    {
       printf("This program does not have \
    /* NOT A COMMENT */ a comment.\n");
    return 0;
    }

The output of the program is:

This program does not have /* NOT A COMMENT */ a comment.

In the following example, the comments are highlighted:

/* A program with nested comments. */

    #include <stdio.h>

    int main(void)
    {
       test_function();
       return 0;
    }

    int test_function(void)
    {
       int number;
       char letter;
    /*
    number = 55;
    letter = 'A';
    /* number = 44; */
    */
    return 999;
    }

In test_function, the compiler reads the first /* through to the first */. The second */ causes an error. To avoid commenting over comments already in the source code, you should use conditional compilation preprocessor directives to cause the compiler to bypass sections of a program. For example, instead of commenting out the above statements, change the source code in the following way:

  /* A program with conditional compilation to avoid nested comments. */

    #define TEST_FUNCTION 0
    #include <stdio.h>

    int main(void)
    {
       test_function();
       return 0;
    }

    int test_function(void)
    {
        int number;
        char letter;
     #if TEST_FUNCTION
       number = 55;
       letter = 'A';
       /*number = 44;*/
     #endif  /*TEST_FUNCTION */
    }

You can nest single line comments within C-style comments. For example, the following program will not output anything:

#include <stdio.h>

   int main(void)
   {
      /*
      printf("This line will not print.\n");
      // This is a single line comment
      // This is another single line comment
      printf("This line will also not print.\n");
      */
      return 0;
   }
Note:
You can also use the #pragma comment directive to place comments into an object module.


[ Top of Page | Previous Page | Next Page | Contents | Index ]