gloopit gloopit - 2 months ago 20x
C Question

How can I write this as a switch statement?

I'm having a little trouble trying to rewrite this collection of if statements as a switch statement.

This isn't an exercise or anything, I just really like the look of switch statements. I'm having trouble figuring it out with a function in the if condition on this however.

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;

Is it possible to do this, is there any benefit or am I wasting time?


As the comments have indicated, you can't. What you can do is make it table-driven, which is probably what @Lambda Ninja intended as more DRY. Something like this?

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;