Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for a maximum unsigned value

Tags:

c++

c

unsigned

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.

like image 895
Shaun Avatar asked Nov 30 '22 09:11

Shaun


1 Answers

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))
    /* ... */
like image 68
icecrime Avatar answered Dec 05 '22 07:12

icecrime