c++ - 测试最大无符号值

标签 c++ c unsigned

这是在 C 和 C++ 代码中测试最大无符号值的正确方法吗:

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

其中 foo 是一个 unsigned int,一个 unsigned short,等等。

最佳答案

对于 C++,我相信您最好使用 numeric_limits来自 <limits> 的模板标题:

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

对于 C,其他人已经指出了 <limits.h> header 和 UINT_MAX .


显然,“允许命名类型的解决方案很简单”,因此您可以:

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

[...]

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

关于c++ - 测试最大无符号值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4539469/

相关文章:

c# - 使用 C# 将连续的结构化数据写入二进制文件

c - 多维指针数组重新分配导致段错误

c++ - 你如何从一个字符串中得到一个 unsigned long?

c - Z3 无符号变量 - 简化

C++ Libcurl 在较大内容的 readfunction 回调中导致写入访问冲突

c++ - 二次筛 - o(1) 代表什么?

c++ - 使用自己的模板所有者 ptr 类分配多维数组

python - C中的输入、拆分和排序

C++ 枚举与 unsigned int 比较

c++ - btDefaultMotionState 的多个实例,全部被忽略,但有一个