Can you write an enumerated type value to an array?

Hello everyone,
I was wondering if you could write an enumerated type value to an array? For example:
 
  enum studentLevel { FRESHMAN, SOPHOMORE, JUNIOR, SENIOR };

From the example, could you have "FRESHMAN" in studentLevel[0] ? instead of 0.
Nothing prevents you from declaring an array of enums:
studentLevel students[] = {FRESHMAN, FRESHMAN, SOPHOMORE, SENIOR};

However, remember: all enums are actually integer under the hood.
Do not wonder, try everything. It will not set your PC on fire probably. For now, try this-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <bits/stdc++.h>
using namespace std;

enum direction { north, south, east, west };

int main()
{
    direction arr[5];
    arr[0] = east;
    arr[2] = west;
    arr[1] = north;
    arr[3] = south;
    arr[4] = east;

    for(int i = 0; i < 5; i++)
    {
        cout << "arr["<< i << "] = ";
        switch(arr[i])
        {
            case north : cout << "north\n"; break;
            case south : cout << "south\n"; break;
            case east : cout << "east\n"; break;
            case west : cout << "west\n";
        }
    }

    return 0;
}
Last edited on
all enums are actually integer under the hood.

More carefully, an integral type. Signed or unsigned.

The compiler is free to use whatever integral type it chooses (which is big enough to store all the values), so you cannot make assumptions about its size.

You can also store enum values in an int array.

Andy
Last edited on
Thanks everyone for your input. This really helps me to move in the right direction.
Topic archived. No new replies allowed.