Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is C++ numeric_limits<enum_type>::max() == 0?

Here's a bit of code that might seem like it would work:

#include <cassert>
#include <limits>

enum test { A = 1 };

int main()
{
    int max = std::numeric_limits<test>::max();
    assert(max > 0);
}

But it fails under both GCC (4.6.2) and clang (2.9) on Linux: max() for enum types is in fact zero! And this remains true even if you use the C++11 enum type specifier to explcitly say what type you want your enum to have.

Why is this? And as for the C++11 behavior, is it something explcitly called for? I could find no mention of it in N2347, the paper on Strongly Typed Enums.

like image 651
John Zwinck Avatar asked Feb 08 '12 21:02

John Zwinck


People also ask

What does Numeric_limits mean in C++?

std::numeric_limits ::digits in C++ with Example Return Value: The function std::numeric_limits<T>::digits returns the number of radix digits that the type can represent without loss of precision.

Which data type is accepted in Numeric_limits C++?

Data types that supports std::numeric_limits() in C++ std::numeric_limits<int>::max() gives the maximum possible value we can store in type int. std::numeric_limits<unsigned int>::max()) gives the maximum possible value we can store in type unsigned int.


1 Answers

std::numeric_limits is specialized in the Standard Library "for each arithmetic type, both floating point and integer, including bool" (§18.3.2.1/2).

Your enumeration test is not one of these types, so the primary template is used. Its behavior is specified by §18.3.2.3/1: "The default numeric_limits<T> template shall have all members, but with 0 or false values."

If you want to know the traits of the underlying type of test, you can use underlying_type:

std::numeric_limits<std::underlying_type<test>::type>::max()

Alternatively, you can specialize numeric_limits for test and have it return the values you want. This is not a particularly good idea, though.

like image 185
James McNellis Avatar answered Oct 21 '22 23:10

James McNellis