命名空間
變體
動作

註解

出自 cppreference.com
< cpp
 
 
C++ 語言
一般主題
前處理器
註解
流程控制
條件執行陳述式
if
疊代陳述式 (迴圈)
for
範圍 for (C++11)
跳躍陳述式
函式
函式宣告
Lambda 函式運算式
inline 指定符
動態例外規範 (直到 C++17*)
noexcept 指定符 (C++11)
例外
命名空間
型別
指定符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
儲存期指定符
初始化
 
 

註解(Comments)用作程式碼內的說明文件。當插入到程式中時,編譯器會有效地忽略它們;它們僅旨在作為閱讀原始碼的人類所使用的筆記。雖然特定的文件格式並非 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 文件 關於 註解
English Deutsch 日本語 中文(简体) 中文(繁體)