命名空间
变体
操作

注释

来自 cppreference.cn
< c

注释是代码中的一种文档。当插入到程序中时,它们实际上会被编译器忽略;它们仅供阅读源代码的人类用作笔记。

目录

[编辑] 语法

/* 注释 */ (1)
// 注释 (2) (C99 起)
1) 通常称为“C 风格”或“多行”注释。
2) 通常称为“C++ 风格”或“单行”注释。

所有注释在翻译阶段 3中从程序中移除,方法是将每个注释替换为单个空白字符。

[编辑] C 风格

C 风格注释通常用于注释大块文本或小段代码;但是,它们也可以用于注释单行。要将文本作为 C 风格注释插入,只需用 /**/ 包围文本。C 风格注释告诉编译器忽略 /**/ 之间的所有内容。虽然它不是 C 标准的一部分,但 /****/ 经常用于指示文档块;这是合法的,因为第二个星号只是被视为注释的一部分。

除了在字符常量字符串字面量或注释中,字符 /* 引入注释。此类注释的内容仅用于识别多字节字符并查找终止注释的字符 */。C 风格注释不能嵌套。

C++ 风格

C++ 风格注释通常用于注释单行文本或代码;但是,它们可以放在一起形成多行注释。要将文本作为 C++ 风格注释插入,只需在文本前加上 // 并在文本后加上换行符。C++ 风格注释告诉编译器忽略 // 和换行符之间的所有内容。

除了在字符常量字符串字面量或注释中,字符 // 引入注释,该注释包括所有多字节字符,直到(但不包括)下一个换行符。此类注释的内容仅用于识别多字节字符并查找终止注释的换行符。C++ 风格注释可以嵌套。

//  y = f(x);   // invoke algorithm

C 风格注释可以出现在 C++ 风格注释中。

//  y = f(x);   /* invoke algorithm */

C++ 风格注释可以出现在 C 风格注释中;这是排除一小段源代码的机制。

/*
    y = f(x);   // invoke algorithms
    z = g(x);
*/
(C99 起)

[编辑] 注释

因为注释在预处理器阶段之前被移除,所以宏不能用于形成注释,并且未终止的 C 风格注释不会从 #include 的文件中溢出。

/* An attempt to use a macro to form a comment. */
/* But, a space replaces characters "//".       */
#ifndef DEBUG
    #define PRINTF //
#else
    #define PRINTF printf
#endif
...  
PRINTF("Error in file %s at line %i\n", __FILE__, __LINE__);

除了注释掉,用于源代码排除的其他机制是

#if 0
    puts("this will not be compiled");
    /* no conflict with C-style comments */
    // no conflict with C++-style comments
#endif

if(0) {
    puts("this will be compiled but not be executed");
    /* no conflict with C-style comments */
    // no conflict with C++-style comments
}

C99 中引入 // 注释在某些罕见情况下是一个破坏性更改。

a = b //*divisor:*/ c
+ d; /* C89 compiles a = b / c + d;
        C99 compiles a = b + d; */

[编辑] 示例

#include <stdio.h>
/*
C-style comments can contain
multiple lines.
*/
 
/* Or, just one line. */
 
// C++-style comments can comment one line.
 
// Or, they can
// be strung together.
 
int main(void)
{
  // The below code won't be run
  // puts("Hello");
 
  // The below code will be run
  puts("World");
 
  // A note regarding backslash + newline.
  // Despite belonging to translation phase 2 (vs phase 3 for comments),
  // '\' still determines which portion of the source code is considered
  // as 'comments':
  // This comment will be promoted to the next line \
  puts("Won't be run"); // may issue a warning "multi-line comment"
  puts("Hello, again");
}

输出

World
Hello, again

[编辑] 参考

  • C17 标准 (ISO/IEC 9899:2018)
  • 6.4.9 注释 (p: 54)
  • C11 标准 (ISO/IEC 9899:2011)
  • 6.4.9 注释 (p: 75)
  • C99 标准 (ISO/IEC 9899:1999)
  • 6.4.9 注释 (p: 66)
  • C89/C90 标准 (ISO/IEC 9899:1990)
  • 3.1.9 注释

[编辑] 另请参阅

C++ 文档,关于 注释