Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

where foo is an unsigned int, an unsigned short, and so on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
677 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

if (foo == std::numeric_limits<unsigned int>::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))
    /* ... */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...