INT_[MIN|MAX] limit macros vs numeric_limits<T>

The other answers mostly have correct information, but it seems that this needs updating for C++11.

In C++11, std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), and std::numeric_limits<T>::lowest() are all declared constexpr, so they can be usable in most of the same contexts as INT_MIN and company. The only exception I can think of is compile-time string processing using the # stringification token.

This means that numeric_limits can be used for case labels, template parameters, etc., and you get the benefit of using it in generic code (try using INT_MIN vs. LONG_MIN in template<typename T> get_min(T t);).

C++11 also brings a solution to the issue James Kanze talks about, by adding std::numeric_limits<T>::lowest(), which gives the lowest finite value for all types, rather than the lowest value for integer types and the lowest positive value for floating-point types.


Pre C++0x, definitely. INT_MIN and INT_MAX are integral constant expressions; numeric_limits<int>::min() and numeric_limits<int>::max() aren't. <climits> is standard C++, and unless you're dealing with templates (where you don't know whether it's int or long), there's really no reason to bother with the overly complicated solution. (Also: if you're writing templates, don't forget that numeric_limits<int>::min() and numeric_limits<double>::min() represent completely different attributes; if you want the minimum possible value, you'll need numeric_limits<T>::is_integer ? numeric_limits<T>::min() : -numeric_limits<T>::max().)


If C++, use numeric_limits, end of.

EDIT: Okay, per the comment by James, not "end of." - exceptions are templates and case labels. But, I cannot see a use for having a case label for either min or max, or a template for them, but I guess I've not seen all possibilities...

I guess my point is that the numeric_limits template is more useful beyond max() and min()...

Tags:

C++