提问人:Kumputer 提问时间:10/5/2023 更新时间:10/5/2023 访问量:50
检测预处理器 #if 中不适当的变量用法
Detect inappropriate variable usage within preprocessor #if
问:
请考虑以下任意但过于简化的代码:
#define CONST_BAR 2
int foo(int x)
{
#if CONST_BAR > 0
return x * CONST_BAR;
#else
return x;
#endif
}
假设我们在多个文件中有许多代码块,这些代码块引用了类似预处理器指令中的CONST_BAR。我想将CONST_BAR重构为一个。问题是,如果我未能成功发现所有以类似方式引用的预处理器指令,我的代码将突然在所有地方都出错:constexpr int
CONST_BAR
constexpr int CONST_BAR = 2;
int foo(int x)
{
#if CONST_BAR > 0
return x * CONST_BAR;
#else
return x;
#endif
}
问题是我使用的编译器(MSVC、clang)都没有发出明显错误使用的错误或警告,并且预处理器指令实际上会计算为 false,从而改变我的函数的行为,而这不是我的意图。我真的打算如下:#if CONST_BAR > 0
int foo(int x)
{
if constexpr (CONST_BAR > 0)
{
return x * CONST_BAR;
}
return x;
}
如何让编译器将其识别为错误,以便我可以纠正它?
答: 暂无答案
评论
#define CONST_BAR !
#if CONST_BAR > 0
CONST_BAR_X
#ifdef CONST_BAR
#if
#if