註釋
來自 cppreference.com
< cpp
註釋作為一種程式碼內文件。當插入到程式中時,它們實際上被編譯器忽略;它們僅供閱讀原始碼的人類用作筆記。儘管具體的文件不屬於 C++ 標準的一部分,但存在一些實用程式可以解析不同文件格式的註釋。
目錄 |
[編輯] 語法
/* 註釋 */ |
(1) | ||||||||
// 註釋 |
(2) | ||||||||
1) 通常稱為“C 風格”或“多行”註釋。
2) 通常稱為“C++ 風格”或“單行”註釋。
所有註釋在翻譯階段 3 被從程式中移除,方法是將每個註釋替換為單個空白字元。
[編輯] C 風格
C 風格註釋通常用於註釋大塊文字,但是,它們也可以用於註釋單行。要插入 C 風格註釋,只需用 /*
和 */
包裹文字;這將導致註釋的內容被編譯器忽略。雖然它不屬於 C++ 標準的一部分,但 /**
和 */
經常用於表示文件塊;這是合法的,因為第二個星號只是被視為註釋的一部分。C 風格註釋不能巢狀。
[編輯] C++ 風格
C++ 風格註釋通常用於註釋單行,但是,多個 C++ 風格註釋可以放在一起形成多行註釋。C++ 風格註釋告訴編譯器忽略 //
和新行之間的所有內容。
[編輯] 注意
因為註釋在預處理階段之前被移除,所以宏不能用於形成註釋,並且未終止的 C 風格註釋不會從 #include 的檔案中溢位。
除了註釋掉,用於原始碼排除的其他機制是
#if 0 std::cout << "this will not be executed or even compiled\n"; #endif
和
if (false) { std::cout << "this will not be executed\n"; }
[編輯] 示例
執行此程式碼
#include <iostream> /* C-style comments can contain multiple lines */ /* or just one */ /************** * you can insert any *, but * you can't make comments nested */ // C++-style comments can comment one line // or, they can // be strung together int main() { // comments are removed before preprocessing, // so ABC is "1", not "1//2134", and "1 hello world" // will be printed #define ABC 1//2134 std::cout << ABC << " hello world\n"; // The below code won't be run // return 1; // The below code will be run return 0; }
輸出
1 hello world
[編輯] 另請參閱
C 文件 關於 註釋
|