如何沉默特定的"零&QUOT的符号意义比较;警告? [英] How to silence a particular "pointless comparison of unsigned with zero" warning?

查看:290
本文介绍了如何沉默特定的"零&QUOT的符号意义比较;警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有类似下面的功能:

Suppose I have a function like the following:

#define LOWER_BOUND 0
#define UPPER_BOUND 42

int is_value_in_range( some_typedef val)
{
    return ((LOWER_BOUND <= val) && (val <= UPPER_BOUND));
}

假设我已经配置了适当的警告,如果 some_typedef 原来是一个无符号的类型,我会得到一个警告,有一个无符号类型的0无谓的比较当然这是真的,这是有道理的。

Assuming that I have warnings configured appropriately, if some_typedef turns out to be an unsigned type I'll get a warning that there's a pointless comparison of an unsigned type with 0. Of course that's true, and it makes sense.

但是,可以说,我的的希望与零检查是在code为一个或多个可能的原因,如:

However, lets say that I do want the check against zero to be in the code for one or more possible reasons, such as:


  • 虽然边界将永远是编译时间常数,他们可能是一些可能改变(与宏可能不现场非常接近的功能)。例如,该范围可以由在选项传递给编译器进行设置。

  • 我可能会喜欢抵御的typedef一个符号类型之后的变化,因为它有可能是的typedef每使用可能不仔细检查,当它改变了。

有没有在这里沉默不报警完全关闭它一个体面的,合理的可移植的方法?

Is there a decent, reasonably portable way to silence the warning here without turning it off completely?

东西依赖于'STATIC_ASSERT() - 一样的功能(这是提供给我)是可以接受的,如果它是合理的。我与突破编译OK,如果类型更改为强迫别人看code。但也可能是需要注意的是的typeof 是不是我可以在所有的编译器,我瞄准。

Something that relies on a 'STATIC_ASSERT()'-like functionality (which is available to me) would be acceptable if it's reasonable. I'm OK with breaking the compile if the type changes to force someone to look at the code. But it might be important to note that typeof isn't something I have available in all the compilers I'm targeting.

我专门找C语言的解决方案,所以在这里的模板都没有任何用处...

I'm specifically looking for C language solutions, so templates aren't any use here...

推荐答案

<击>如果 some_typedef 不知道是无符号数,我认为你是pretty太多的运气。

If some_typedef is not known to be unsigned or signed, I think you're pretty much out of luck.

如果你事先知道 some_typedef 是无符号,你可以只使用

If you know in advance that some_typedef is unsigned, you could just use

#if LOWER_BOUND > 0
    return ((LOWER_BOUND <= val) && (val <= UPPER_BOUND));
#else
    return ((val <= UPPER_BOUND));
#endif

或在这种情况下,你可以用我的preferred版本:

Or in this case, you could use my preferred version:

    return (val-LOWER_BOUND <= UPPER_BOUND-LOWER_BOUND);

编辑:我要承担,如果 some_typedef 不知道是特定的符号性的,那么 UPPER_BOUND LOWER_BOUND 都必须是积极的。否则,你将不得不从 some_typedef 很古怪的结果获得晋升为无符号。因此,你总是可以安全地使用:

I'm going to assume if some_typedef is not known to be of particular signedness, then UPPER_BOUND and LOWER_BOUND must both be positive. Otherwise you would have very wacky results from some_typedef getting promoted to unsigned. Thus, you could always safely use:

    return ((uintmax_t)val-LOWER_BOUND <= UPPER_BOUND-LOWER_BOUND);

这篇关于如何沉默特定的&QUOT;零&QUOT的符号意义比较;警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆