Skip to main content
1 of 2

Alternative to multiple if statements?

Just started this problem set about a day or two ago and while implementing lookup I was wondering if there was an alternative to using multiple if statements to compare the path and return the MIME type.

Just curious in an effort to not be copy and pasting lines of code to avoid bad design!

Currently I have the following as my lookup implementation.

const char* lookup(const char* path)
{
    // sets a pointer to the first index in path where '.' is found
    char* dot = strchr(path, '.');
    if (dot == NULL)
    {
        return NULL;
    }
    
    // compares dot with file type returning MIME type
    if (strcasecmp(dot, ".html") == 0)
    {
        return "text/html";
    }
    if (strcasecmp(dot, ".css") == 0)
    {
        return "text/css";
    }
    if (strcasecmp(dot, ".gif") == 0)
    {
        return "image/gif";
    }
    if (strcasecmp(dot, ".ico") == 0)
    {
        return "image/x-icon";
    }
    if (strcasecmp(dot, ".jpg") == 0)
    {
        return "image/jpeg";
    }
    if (strcasecmp(dot, ".js") == 0)
    {
        return "text/javascript";
    }
    if (strcasecmp(dot, ".php") == 0)
    {
        return "text/x-php";
    }
    if (strcasecmp(dot, ".png") == 0)
    {
        return "image/png";
    }    
    else
    {
        return NULL;
    }
}

Any help is greatly appreciated!