c - 如何将其写成 switch 语句?

标签 c if-statement switch-statement

我在尝试将这个 if 语句集合重写为 switch 语句时遇到了一些麻烦。

这不是练习或任何东西,我真的很喜欢 switch 语句的外观。但是,我无法通过 if 条件中的函数来解决这个问题。

const char* lookup(const char* path)
{
    //if a path exists, compare path to given extensions
    //if there is a match, return the appropriate output
    if (path != NULL) {
        //using strcasecmp is useful b/c capitalization is overlooked when looking for a match
        if (strcasecmp(path, "CSS") == 0) return "text/css";
        if (strcasecmp(path, "HTML") == 0) return "text/html";
        if (strcasecmp(path, "GIF") == 0) return "image/gif";
        if (strcasecmp(path, "ICO") == 0) return "image/x-icon";
        if (strcasecmp(path, "JPG") == 0) return "image/jpeg";
        if (strcasecmp(path, "JS") == 0) return "text/javascript";
        if (strcasecmp(path, "PHP") == 0) return "text/x-php";
        if (strcasecmp(path, "PNG") == 0) return "image/png";
    }
    //if there is no path, return NULL
    return NULL;
}

是否可以这样做,有任何好处还是我在浪费时间?

最佳答案

正如评论所指出的,你不能。你可以做的是让它成为表驱动的,这可能是@Lambda Ninja 想要更干的。是这样的吗?

typedef struct pair_s {
    const char *first;
    const char *second;
} pair;

const char *lookup(const char *path)
{
    static pair content_types[] = {
        { "CSS", "text/css" },
        { "HTML", "text/html" },
        { "GIF", "image/gif" },
        { "ICO", "image/x-icon" },
        // ... etc.
        { "", "" }, // terminator
    };

    for (int i = 0; *content_types[i].first != '\0'; i++) {
        if (strcasecmp(path, content_types[i].first) == 0)
            return content_types[i].second;
    }

    return NULL;
}

关于c - 如何将其写成 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38861473/

相关文章:

libevent `struct event` 变量可以修改吗?

c - 这个clear_mem函数的目的是什么?

swift - 有没有办法缩短其中包含 arc4random_uniform( ) 的 if 语句?

java - 声明与。堵塞

Android - SharedPreferences - 根据偏好值调整代码?

c - 使用 fgets() 扫描空白区域

c++ - 在 C 或 C++ 中定义结构的宏

javascript - 使用 if 语句更改 javascript 中的 location.href

Java 扫描仪不返回多字变量

javascript - (如何)我可以在 switch 语句中使用 'or' 吗?