枚举的一种用法记录

常用方法

#include 

enum week {
    Mon = 1, 
    Tues, 
    Wed, 
    Thurs, 
    Fri, 
    Sat, 
    Sun
};

int main(){
    week day;
    for (day= Mon; day <= Sun; day=week(day+1)){
        switch(day){
            case Mon: puts("Monday"); break;
            case Tues: puts("Tuesday"); break;
            case Wed: puts("Wednesday"); break;
            case Thurs: puts("Thursday"); break;
            case Fri: puts("Friday"); break;
            case Sat: puts("Saturday"); break;
            case Sun: puts("Sunday"); break;
            default: puts("Error!");
        }
    }
    
    return 0;
}

巧用宏定义

#include 

#define __WEEK_DEFINE_TABLE(XX)   \
    XX(Mon,        1,     "Monday")          \
    XX(Tues,       2,     "Tuesday")         \
    XX(Wed,        3,     "Wensday")         \
    XX(Thurs,      4,     "Thursday")        \
    XX(Fri,        5,     "Friday")          \
    XX(Sat,        6,     "Saturday")        \
    XX(Sun,        7,     "Sunday")          \

enum week {
#define XX(name, number, desc) name = number,
    __WEEK_DEFINE_TABLE(XX)
#undef XX
    Error
};

int main(){
    week day;
    for (day= Mon; day <= Sun; day=week(day+1)){
        switch(day){
            case Mon: puts("Monday"); break;
            case Tues: puts("Tuesday"); break;
            case Wed: puts("Wednesday"); break;
            case Thurs: puts("Thursday"); break;
            case Fri: puts("Friday"); break;
            case Sat: puts("Saturday"); break;
            case Sun: puts("Sunday"); break;
            default: puts("Error!");
        }
    }
    
    return 0;
}

这种方式特别适合定义错误码

进一步改进,优化switch逻辑

#include 

#define __WEEK_DEFINE_TABLE(XX)   \
    XX(Mon,        1,     "Monday")          \
    XX(Tues,       2,     "Tuesday")         \
    XX(Wed,        3,     "Wensday")         \
    XX(Thurs,      4,     "Thursday")        \
    XX(Fri,        5,     "Friday")          \
    XX(Sat,        6,     "Saturday")        \
    XX(Sun,        7,     "Sunday")          \

enum week {
#define XX(name, number, desc) name = number,
    __WEEK_DEFINE_TABLE(XX)
#undef XX
    Error
};

const char *week2name(week day)
{
#define XX(name, number, desc)  case name: return #name;
    static char buf[24];
    switch (day)
    {
        __WEEK_DEFINE_TABLE(XX)
        
    default:
        sprintf(buf, "Unknown(%d)", day);
        return buf;
    }
#undef XX
}

const char *week2desc(week day)
{
#define XX(name, number, desc) case name: return #name ": " desc;
    static char buf[24];
    switch (day)
    {
        __WEEK_DEFINE_TABLE(XX)

    default:
        sprintf(buf, "Unknown(%d)", day);
        return buf;
    }
#undef XX
}

int main(){
    week day;
    for (day= Mon; day <= Sun; day=week(day+1)){
        printf("%s\n",week2name(day));
        printf("%s\n",week2desc(day));
    }
    
    return 0;
}

你可能感兴趣的:(枚举的一种用法记录)