Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum C++ Get by Index

Tags:

c++

enums

I was wondering in C++ if I have an enum can I access the value at the second index? For example I have

enum Test{hi, bye};

if I want 'hi', can I do something like Test[0], thanks.


1 Answers

Yes and no. If your Enum does not have explicit values then it is possible. Without an explicit values, enum values are given numeric values 0-N in order of declaration. For example ...

enum Test {
  hi, // 0
  bye // 1
}

This means that indexes just translates into a literal value.

Test EnumOfIndex(int i) { return static_cast<Test>(i); }

This of course does 0 validation at runtime and as soon as you add an explicit value it will break down. But it will work in the default scenario.

like image 116
JaredPar Avatar answered Sep 13 '25 06:09

JaredPar