Reputation: 2287
What is the range of a c++ enum with a constant expression? This is my code
#include <iostream>
int main(){
enum e3{min = -10, max = 100000};
e3 x = e3(-1000);
e3 y= e3(-100000912241);
std::cout<<x<<" "<<y<<std::endl;
}
It outputs -1000 -1216664433
How is this happening?
Also, The C++ programming language by Bjarne Stroustrup
specifies that the result of conversion of integral type to enumeration is undefined unless the value is the within the range of the enumeration. What is this range and how to calculate it?
Upvotes: 0
Views: 337
Reputation: 234665
The range of an enum
is the range of the underlying type. The compiler has probably selected an int
as the underlying type of your enum
.
It's allowed to do that since an int
(assuming it's 32 bit on your platform) can contain all the explicit values you've given it.
You'll probably find that the type of -100000912241
is a long
or a long long
on your platform (note there is no such thing as a negative literal in C++: -100000912241
is the unary negation of the literal 100000912241
.). But -100000912241
can't fit into that int
, so the behaviour of your code is undefined.
If you want to inspect the underlying type of an enum
, then use std::underlying_type
.
Reference: http://en.cppreference.com/w/cpp/types/underlying_type
Upvotes: 4