註釋
來自 cppreference.com
< c
註釋是程式碼中的一種文件。當插入到程式中時,它們實際上會被編譯器忽略;它們僅供閱讀原始碼的人類用作筆記。
目錄 |
[編輯] 語法
/* 註釋 */ |
(1) | ||||||||
// 註釋 |
(2) | (C99 起) | |||||||
1) 通常稱為“C 風格”或“多行”註釋。
2) 通常稱為“C++ 風格”或“單行”註釋。
所有註釋在翻譯階段 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 的檔案中溢位。
/* 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++ 文件,關於 註釋
|