Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Pros/Cons of Enum-Indexed Arrays [closed]

In my experience, the real world rarely provides for indexes of nonnegative integers. Many things aren't even represented numerically. And many things with a numerically-represented index don't begin their indexes at 0. Why then are we still limited to integer-indexed arrays?

Maybe I'm wrong, but it seems like enum indexed arrays are often more appropriate than numerically-indexed arrays (as enums are often more accurate, "real-world" representations). While enums can often be translated into C-style array indices with relative ease...

enum Weekday = {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
}

// hopefully C doesn't allow nonsequential enum values; else pray to God
// no one does something like setting Sunday = 4 and Saturday = 4096
int numberOfDays = Saturday-Sunday+1;

int hoursWorkedPerDay[numberOfDays];

hoursWorkedPerDay[(int)SUNDAY] = 0;
hoursWorkedPerDay[(int)MONDAY] = 8;
hoursWorkedPerDay[(int)TUESDAY] = 10;
hoursWorkedPerDay[(int)WEDNESDAY] = 6;
hoursWorkedPerDay[(int)THURSDAY] = 8;
hoursWorkedPerDay[(int)FRIDAY] = 8;
hoursWorkedPerDay[(int)SATURDAY] = 0;

...we are still required to maintain consistency between the number of enums and the size of the array (however, this isn't an awful solution because there's not a more valid integer mapping for "SUNDAY" than 0), and more importantly, anything that can be cast to an int could still be dropped into the index to manipulate the array:

// continued from above
void resetHours (void) {
    int i = 0;
    int hours = 0;
    for (i = 0; i<numberOfDays; i++) {
        hoursWorkedPerDay[hours] = i;
        // oops, should have been: "...[i] = hours;"
        // an enum-indexed implementation would have caught this
        // during compilation
    }
}

Furthermore, the entire conversion from enum to int is an entire layer of complexity that seems unnecessary.

Can someone please explain whether there is validity to enum-indices, and list some pros and cons to each approach? And perhaps why a feature so seemingly useful is missing from the C standard, if such information exists?

like image 212
weberc2 Avatar asked Nov 06 '12 18:11

weberc2


People also ask

Why is an enum better than an array?

The main difference is that an array is a value and an enum is a type. And One main difference we can say that an array is a collection of other values (that is it contains other values, you can iterate through them or access individual ones by index), whereas an enum value is simply one atomic value.


1 Answers

If you really want to use the enum as index you should declare the integer values explicitly.

On the other hand I personally would prefer s.th. type safe (i.e. without the ugly cast, that might even not be necessary), like:

std::map<Weekday,int> hoursWorkedPerDay;
like image 75
πάντα ῥεῖ Avatar answered Oct 16 '22 11:10

πάντα ῥεῖ