ice*_*ime 12
对于C++,我相信你最好使用标题中的numeric_limits模板<limits>:
if (foo == std::numeric_limits<unsigned int>::max())
/* ... */
Run Code Online (Sandbox Code Playgroud)
对于C,其他人已经指出了<limits.h>标题和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))
/* ... */
Run Code Online (Sandbox Code Playgroud)
我想你问这个问题,因为在某个时刻你不知道变量的具体类型foo,否则你自然会使用UINT_MAX等等.
对于C,您的方法仅适用于转换级别为int或更高的类型.这是因为在比较之前unsigned short,例如int,如果所有值都适合,则首先转换为值,或者unsigned int否则.那么你的价值foo将被比作-1或UINT_MAX不是你所期望的.
我没有看到在C中实现您想要的测试的简单方法,因为基本上使用foo任何类型的表达式都会将其推广到int.
使用gcc的typeof扩展,这很容易实现.你只需要做类似的事情
if (foo == (typeof(foo))-1)
Run Code Online (Sandbox Code Playgroud)