Search code examples
cfunctioncharconstantsfree

The const char* should it be freed in C?


Please consider the following code. I am asking if this is correct, is there something missing. Is there any other way to make it.

#include <stdio.h>
#include <string.h>
const char *getOrder (const char *day)
{
    if (strncmp(day, "Monday", 7) == 0) {
        return "first";
    } else if (strncmp(day, "Tuesday", 7) == 0) {
        return "second";
    } else if (strncmp(day, "Wednesday", 9) == 0) {
        return "third";
    } else if (strncmp(day, "Thursday", 8) == 0) {
        return "forth";
    } else if (strncmp(day, "Friday", 6) == 0) {
        return "fifth";
    } else if (strncmp(day, "Saturday", 8) == 0) {
        return "sixth";
    } else if (strncmp(day, "Sunday", 6) == 0) {
        return "seventh";
    } else
        return NULL;
}
int main()
{
    const char* str = NULL;
    str = getOrder ("Monday");
    printf("str : %s\n", str);
    return 0;
}

Solution

  • The if/else ladder is overly complicated and prone to 'copy/paste' errors.

    It seems you want a "look up table" to translate a weekday name to a different string.

    const char *getOrder (const char *day) {
        char *LUT[][2] = {
        { "Monday", "first", },
        { "Tuesday", "second", },
        { "Wednesday", "third", },
        { "Thursday", "forth", },
        { "Friday", "fifth", },
        { "Saturday", "sixth", },
        { "Sunday", "seventh", },
        };
        
        for( i = 0; i < sizeof(LUT)/sizeof(LUT[0]); i++ )
            if( strncmp(day, LUT[i][0], strlen( LUT[i][0] ) ) == 0 )
                return LUT[ i ][ 1 ];
    
        return "NOT A DAY NAME";
    }
    

    It's still iteratively hunting...

    Here is a tiny hash function to quickly translate string day names to an integer value (case insensitive). Play with it. Perhaps you will try to adapt this to go straight to the plausible weekday name.

    // Convert a day name (or 3 letter abbrev.) to index (1-7, Sun=1). Beware false positives!
    static int wkdayOrd( char cp[] ) { return "65013427"[*cp/2 + ~cp[1] & 0x7] & 0x7; }