By pure chance when trying to understand a build error of some C++ code I'm working on, I came across the correct C++ way of checking for numeric limits. Here is how.

In C, when you need to check for the limits of native numeric types, such as int or unsigned long, you include the limits.h header file and then use the INT_MIN/INT_MAX and ULONG_MAX macros respectively. In the C++ world, there is a corresponding climits header file to get the definition of these macros, so I always thought this was the way to follow.

However, it turns out that the C++ standard defines a limits header file too, which provides the numeric_limits<T> template. This template class is specialized in T for every numeric type and provides a set of static methods to query properties about the corresponding type. The simplest ones are min() and max(), which are what we need to replace the old-style *_MIN and *_MAX macros.

As an example, this C code:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
printf("Integer range: %d to %dn", INT_MIN, INT_MAX);
return EXIT_SUCCESS;
}
becomes the following in C++:
#include <cstdlib>
#include <iostream>
#include <limits>

int
main(void)
{
std::cout << "Integer range: "
<< std::numeric_limits< int >::min()
<< " to "
<< std::numeric_limits< int >::max()
<< "n";
return EXIT_SUCCESS;
}
Check out the documentation for more details on additional methods!

Comments from the original Blogger-hosted post: