How do I get the index of a value in an enum?


I know that RED has index 0 and BLUE has index 1, but how do I find that out using
code?

I tried using std::cout << Colors.RED; but the compiler throws an error.

Thanks to those that answer.

1
2
3
4
5
6
enum Colors {RED, BLUE};

int main()
{
    return 0;
}
Something like this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int main()
{
	enum COLORS {RED , BLUE};
	int choice;
	cin>>choice;
	switch (choice)
	{
	case 0:
		cout<<RED<<endl;
		break;
	case 1:
		cout<<BLUE<<endl;
		break;
	default:
		exit(0);
	}
	return 0;
}


Red is 0, Blue is 1.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

enum Colors { RED /* = 0 */ , BLUE /* = RED+1 */ }; // unscoped enum

enum class Forums { BEGINNERS = 87, GENERAL_PRGRAMMING /* = 88 */ }; // scoped enum

// see: http://en.cppreference.com/w/cpp/language/enum

int main()
{
    std::cout << BLUE << '\n' // BLUE is implicitly converted to integer
          << int( Forums::BEGINNERS ) << '\n' ; // scoped enum needs explicit conversion
    // in C++, we use :: for scope resolution; Forums::BEGINNERS
}
Thank you!
Topic archived. No new replies allowed.