gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:34:56 25 4
gpt4 key购买 nike

我在尝试将这个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com