测试最长的无符号数 [英] Testing for a maximum unsigned value

查看:103
本文介绍了测试最长的无符号数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是测试C和C ++ code的最高值,无符号的正确方法是:

Is this the correct way to test for a maximum unsigned value in C and C++ code:

if(foo == -1)
{
    // at max possible value
}

其中foo是 unsigned int类型,一个无符号短,等等。

推荐答案

对于C ++,我相信你应该preferably使用 numeric_limits 模板从的 <限制和GT; 标题:

For C++, I believe you should preferably use the numeric_limits template from the <limits> header :

if (foo == std::numeric_limits<unsigned int>::max())
    /* ... */

有关C,其他人已经指出, &LT; limits.h中方式&gt; 头和 UINT_MAX

For C, others have already pointed out the <limits.h> header and UINT_MAX.

显然,被允许命名类型的解决方案是很容易,所以你可以有:

Apparently, "solutions which are allowed to name the type are easy", so you can have :

template<class T>
inline bool is_max_value(const T t)
{
    return t == std::numeric_limits<T>::max();
}

[...]

if (is_max_value(foo))
    /* ... */

这篇关于测试最长的无符号数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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