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++风格”或“单行”注释。

所有注释在 翻译阶段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 << "此代码将不会被执行\n";
}

示例

#include <iostream>
/* C风格注释可以包含
多行内容 */
/* 或仅有一行 */
/**************
 *  可以插入任意数量的 *,但
 *  不能嵌套注释
 */
// C++风格注释可以注释单行
// 或者,它们可以
// 连续拼接使用
int main()
{
    // 注释在预处理阶段会被移除,
    // 因此 ABC 的值是 "1" 而非 "1//2134",将输出
    // "1 hello world"
#define ABC 1//2134
    std::cout << ABC << " hello world\n";
    // 以下代码不会执行
    // return 1;
    // 以下代码将会执行
    return 0;
}

输出:

1 hello world

参见

C 文档 关于 comment