注释

注释 是在预处理期间由单个空格字符替换的文本; 因此,编译器将忽略所有注释。

有两种评论:
  • /* (斜杠,星号) 字符,后跟任意字符序列 (包括新行) ,后跟 */ 字符。 此类注释通常称为 C 样式注释
  • // (两个斜杠) 字符后跟任何字符序列。 没有紧跟在反斜杠前面的新行将终止此格式的注释。 此类注释通常称为 单行注释C++ 注释如果 C++ 注释使用行连续 (\) 字符连接到一个逻辑源行中,那么它可以跨多个物理源行。 反斜杠字符也可以由三字符表示。

您可以在语言允许空格的任何位置放置注释。 不能将 C 样式的注释嵌套在其他 C 样式的注释中。 每个注释在第一次出现 */时结束。

您还可以包含多字节字符; 要指示编译器识别源代码中的多字节字符,请使用 -qmbcs 选项进行编译。

注: 在字符常量或字符串文字中找到的 /**/ 字符不会开始或结束注释。
在以下程序中,第二个 printf() 是注释:
 #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;
 }
由于第二个 printf() 等效于空间,因此此程序的输出为:
This program has a comment.
由于注释定界符位于字符串文字中,因此以下程序中的 printf() 不是注释。
#include <stdio.h>

    int main(void)
    {
       printf("This program does not have \
    /* NOT A COMMENT */ a comment.\n");
    return 0;
    }
程序的输出为:
This program does not have
/* NOT A COMMENT */ a comment.
在以下示例中,将突出显示注释:
/* 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;
    }
test_function中,编译器会将第一个 /* 读取到第一个 */。 第二个 */ 会导致错误。 为了避免对源代码中已有的注释进行评论,您应该使用条件编译预处理器伪指令来使编译器绕过程序的部分。 例如,改为通过以下方式更改源代码,而不是注释掉上述语句:
  /* 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 */
    }
您可以将单行注释嵌套在 C 样式的注释中。 例如,以下程序不会输出任何内容:
#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;
   }
注: 您还可以使用 #pragma comment 伪指令将注释放入对象模块中。