0

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?

Krash
  • 2,085
  • 3
  • 13
  • 36
  • I recommend not using enums values as integers. It is a bad design as this is not the purpose of usage of them. Maybe `struct` is a good replacement. That is why c++ prefers [enum class](https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum)es over typical enums. – Arash Nov 17 '17 at 08:32

1 Answers1

4

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • It makes sense but what is the range of an enum? Is an enum supposed to accept all integral values or only values within a particular range based on its initialisation – Krash Nov 17 '17 at 08:29
  • @Krash: Added that to the answer. – Bathsheba Nov 17 '17 at 08:30