Comments
注释在代码中起到一种文档的作用。当插入到程序中时,编译器实际上会忽略它们;它们纯粹是为了让阅读源代码的人能够用作笔记。
目录 |
语法
/*
注释
*/
|
(1) | ||||||||
//
注释
|
(2) | (自 C99 起) | |||||||
在 翻译阶段3 ,程序中的所有注释会被移除,具体方式是将每个注释替换为单个空白字符。
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引入的文件中溢出。
/* 尝试使用宏来构成注释 */ /* 但空格会替换字符"//" */ #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("这段代码会被编译但不会被执行"); /* no conflict with C-style comments */ // no conflict with C++-style comments }
C99中引入//注释在某些罕见情况下是一个破坏性变更:
a = b //*divisor:*/ c + d; /* C89 编译为 a = b / c + d; C99 编译为 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 注释(页码:66)
- C89/C90 标准 (ISO/IEC 9899:1990):
-
- 3.1.9 注释
参考
|
C++ 文档
关于
Comments
|