C - Enum-Indexed Arrays的优点/缺点

web*_*rc2 6 c c++ arrays indexing enums

根据我的经验,现实世界很少提供非负整数的索引.许多事情甚至没有用数字表示.许多带有数字表示索引的东西都不会将它们的索引开始为0.为什么我们仍然只限于整数索引数组呢?

也许我错了,但似乎枚举索引数组通常比数字索引数组更合适(因为枚举通常更准确,"真实世界"表示).虽然枚举通常可以相对轻松地转换为C风格的数组索引...

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;
Run Code Online (Sandbox Code Playgroud)

...我们仍然需要保持枚举数和数组大小之间的一致性(但是,这不是一个糟糕的解决方案,因为"SUNDAY"没有比0更有效的整数映射,更重要的是,任何可以强制转换为int的东西仍然可以放入索引来操作数组:

// 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
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,从enum到int的整个转换是整个复杂层,似乎是不必要的.

有人可以解释一下enum-indices是否有效,并列出每种方法的优缺点?也许为什么如果这样的信息存在,C标准中缺少一个看似有用的功能?

Omk*_*ant 2

Sunday =0 //by default, if you won't mention explicit value then it would take 0
Run Code Online (Sandbox Code Playgroud)

Saturday = 6 // as in your example

所以

int numberOfDays = Saturday-Sunday; // which is 6 

int hoursWorkedPerDay[numberOfDays]; 
Run Code Online (Sandbox Code Playgroud)

数组只有 6 个位置来保存值。

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;  
Run Code Online (Sandbox Code Playgroud)

访问数组索引(即 6)之外的行为是未定义的行为