抑制警告:由于数据类型范围有限,比较总是为假 [英] Suppressing warning: comparison is always false due to limited scope of data type

查看:331
本文介绍了抑制警告:由于数据类型范围有限,比较总是为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板函数用于返回数字中的数字位数:

I have a templated function for returning the number of digits in a number:

    template <typename R>
    static inline unsigned count(const R num)
    {
        if(num < 10)                    return 1;
        else if (num < 100)             return 2;
        else if (num < 1000)            return 3;
        else if (num < 10000)           return 4;
        else if (num < 100000)          return 5;
        else if (num < 1000000)         return 6;
        else if (num < 10000000)        return 7;
        else if (num < 100000000)       return 8;
        else if (num < 1000000000)      return 9;
        else if (num < 10000000000ULL)          return 10;
        else if (num < 100000000000ULL)         return 11;
        else if (num < 1000000000000ULL)        return 12;
        else if (num < 10000000000000ULL)       return 13;
        else if (num < 100000000000000ULL)      return 14;
        else if (num < 1000000000000000ULL)     return 15;
        else if (num < 10000000000000000ULL)    return 16;
        else if (num < 100000000000000000ULL)   return 17;
        else if (num < 1000000000000000000ULL)  return 18;
        else if (num < 10000000000000000000ULL) return 19;
        else                                    return 20;
    }


$ b >

However when I compile (GCC) I get the following warning:

warning: comparison is always true due to limited range of data type

我明白为什么我反复收到这个消息,但我不知道如何禁止/避免它。

I understand why I get this repeatedly but I'm not sure how to suppress/avoid it.

推荐答案

如果你不关心用户定义的整数类型(并且证据表明你不关心负值),只需定义一个函数,该函数采用您所关心的最大类型:

If you don't care about user-defined integer types (and evidence suggests that you don't care about negative values, either), just define one function which takes the largest type that you care about:

inline unsigned count(unsigned long long num){
    if(num < 10)                    return 1;
    else if (num < 100)             return 2;
    // blah blah
    else return 20;
}



如果您使用 code>或者什么,你不会得到任何关于隐式转换的警告,因为它是一个加宽。

If you call it with a signed short or whatever, you won't get any warnings about the implicit conversion, since it's a widening.

static_cast< unsigned& (log10(num))+ 1 也值得剖析。

这篇关于抑制警告:由于数据类型范围有限,比较总是为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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