Namespaces
Variants

Comments

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

コメントは一種のコード内ドキュメントとして機能します。プログラムに挿入されると、それらはコンパイラによって事実上無視されます。コメントは、ソースコードを読む人間がメモとして使用することを目的としています。特定のドキュメントはC++標準の一部ではありませんが、さまざまなドキュメント形式でコメントを解析するいくつかのユーティリティが存在します。

目次

構文

/* コメント */ (1)
// コメント (2)
1) しばしば「Cスタイル」または「複数行」コメントとして知られています。
2) しばしば「C++スタイル」または「単一行」コメントとして知られています。

すべてのコメントはプログラムから translation phase 3 で削除され、各コメントは単一の空白文字で置き換えられます。

Cスタイル

Cスタイルコメントは通常、大きなテキストブロックをコメントアウトするために使用されますが、単一行のコメントにも使用できます。Cスタイルコメントを挿入するには、テキストを /* */ で囲みます。これにより、コンパイラはコメントの内容を無視します。C++標準の一部ではありませんが、 /** */ はドキュメンテーションブロックを示すためによく使用されます。これは2つ目のアスタリスクが単にコメントの一部として扱われるため、合法です。Cスタイルコメントはネストできません。

C++スタイル

C++スタイルのコメントは通常単一行のコメントに使用されますが、複数のC++スタイルコメントを連続して配置することで複数行のコメントを形成できます。C++スタイルのコメントは、 // から改行までのすべての内容をコンパイラが無視するように指示します。

注記

コメントは 削除される ため、マクロを使用してコメントを形成することはできず、終端がないCスタイルのコメントが#includeされたファイルから溢れ出すこともありません。

コメントアウト以外に、ソースコードの除外に使用される他のメカニズムは以下の通りです。

#if 0
    std::cout << "このコードは実行もコンパイルもされません\n";
#endif

and

if (false)
{
    std::cout << "これは実行されません\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 documentation for comment