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

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

c++ - Testing for a maximum unsigned value

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

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

1 Answer

0 votes
by (71.8m points)

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))
    /* ... */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...