1. 基础知识
最基本的要求: 字母、数字、下划线组成, 并且不能是数字开头。
禁忌1: C++ 关键字不能用做标识符。 它们是:
alignas alignof asm auto
bool break
case catch char char16_t char32_t class const constexpr const_cast continue
decltype default delete do double dynamic_cast
else enum explicit export extern
false float for friend
goto
if inline int long mutable
namespace new noexcept nullptr
operator
private protected public
register reinterpret_cast return
short signed sizeof static static_assert static_cast struct switch
template this thread_local throw true try typedef typeid typename
union unsigned using
virtual void volatile
wchar_t while
禁忌2:不能包含两个连续的下划线。
禁忌3:不能以下划线 + 大写字母开头。
禁忌4:函数外面定义的标识符, 不能以下划线开头。
禁忌5:宏定义也是 identifier,也需要遵循前面提到的要求: https://en.cppreference.com/w/cpp/preprocessor/replace
禁忌6:和已有宏定义同名, 例如 #include <windows.h> 后, 默认会引入 small/min/max 等宏定义, 会导致无法使用它们作为变量名字(编译报错).
2. 规则太多,记不住?
用 clang 编译器。 指定 -Werror=reserved-identifier
编译选项。
给一个富含各种 reserved identifier 的内容
#define _ENABLE_TEST 1
int _Count;
int _monster;
int main()
{
int hello__world;
int _Kali;
int _yes;
return 0;
}
这份代码中只有 _yes
是合法 identifier, 其他都和 reserved identifier 冲突了。
编译:检测到了每一处非法的identifier 命名
g++ test39.cpp -std=c++11 -Werror=reserved-identifier