C++标识符:检查是否和保留字冲突

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值