Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max and min values in a C++ enum

Tags:

c++

enums

Is there a way to find the maximum and minimum defined values of an enum in c++?

like image 230
Matt Avatar asked Oct 01 '08 18:10

Matt


People also ask

What is sizeof enum in C?

In C language, an enum is guaranteed to be of size of an int . There is a compile time option ( -fshort-enums ) to make it as short (This is mainly useful in case the values are not more than 64K). There is no compile time option to increase its size to 64 bit.

Can enum have float values in C?

Enums can only be ints, not floats in C# and presumably unityScript.

Can enum values be compared in C?

C static code analysis: Values of different "enum" types should not be compared.


2 Answers

No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,

enum MyPretendEnum {    Apples,    Oranges,    Pears,    Bananas,    First = Apples,    Last = Bananas }; 

There do not need to be named values for every value between First and Last.

like image 118
Jeff Yates Avatar answered Sep 24 '22 08:09

Jeff Yates


No, not in standard C++. You could do it manually:

enum Name {    val0,    val1,    val2,    num_values }; 

num_values will contain the number of values in the enum.

like image 36
dalle Avatar answered Sep 26 '22 08:09

dalle