[英]Ignore dead code warnings in C/ C++
Having the following code (greatly simplified): 具有以下代码(已大大简化):
#define DO_SOME_STUFF(val,x,y) \
if (x>y) \
{ \
val = val >> (x-y); \
} else { \
val = val >> (y-x); \
}
An example of calling the macro with expansion will be: 用扩展调用宏的示例将是:
int val = 5;
DO_SOME_STUFF(val,5,10);
=>
if (5>10)
{
// dead code
val = val >> (5-10); // negative shift warning here
} else {
// live code
val = val >> (10-5); // valid code
}
Now, since there is dead code, it will be removed by the compiler and everyone will be happy since I will never negative shift - so I'm doing legal stuff here. 现在,由于存在无效代码,编译器将删除它们,并且每个人都会感到高兴,因为我永远不会出现负面变化-所以我在这里做合法的事情。
Unfortunately, I receive the warnings before the code gets removed (or so it seems). 不幸的是,我在删除代码之前收到警告(或者看起来如此)。
In the project I'm working the function will be called 100+ times, and the only solution I came up so far is to do the following: 在我正在工作的项目中,该函数将被调用100次以上,到目前为止,我提出的唯一解决方案是执行以下操作:
#pragma GCC diagnostic ignored "-Wshift-count-negative"
DO_SOME_STUFF(val,300,20);
#pragma GCC diagnostic pop
This isn't very nice, since i will add a ton of these which will result in hard-to-read blue code, and I would rather avoid it if possible. 这不是很好,因为我将添加大量的代码,这将导致难以理解的蓝色代码,如果可能的话,我宁愿避免这样做。
Is there an elegant way to remove the warning just for my macro expansion or to ask the compiler to ignore dead code ? 有没有一种优雅的方法可以删除仅针对宏扩展的警告或要求编译器忽略无效代码? (unfortunately i cannot add the #pragma options to my macro definition). (不幸的是,我无法将#pragma选项添加到宏定义中)。
In c++11 you could use a template constexpr
function instead of the macro. 在c ++ 11中,可以使用模板constexpr
函数代替宏。 It can then be executed during the compilation and will not produce a warning. 然后可以在编译期间执行它,并且不会产生警告。
template <typename T, typename T2>
constexpr T do_some_stuff(const T& val, const T2& x, const T2& y)
{
return x > y ? val >> (x - y) : val >> (y - x);
}
template <typename T, typename T2>
constexpr T do_some_stuff_wrong(const T& val, const T2& x, const T2& y)
{
return x < y ? val >> (x - y) : val >> (y - x);
}
int main()
{
constexpr int val = do_some_stuff(5, 5, 10); // no warning
constexpr int val2 = do_some_stuff_wrong(5, 5, 10); // warning
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.