Search code examples
cswitch-statementstrcmp

using (char*) in switch statement


I am new in C programming language and have an (if statement) and need to transfer it into switch statement. My problem is that I have a field named (node_kind) of char* type and I compare it's content in the if statement using (strcmp) but I don't know how to do that in the switch statement. Would you plz tell me how ? Here is a short quote of my program

if (strcmp(node->node_kind, "VAR_TOKEN_e") == 0) 
    job = visitor->visitjob_VAR_TOKEN; 
if (strcmp(node->node_kind, "INT_e") == 0) 
    job = visitor->visitjob_int; 
if (strcmp(node->node_kind, "BOOL_e") == 0) 
    job = visitor->visitjob_bool; 

Solution

  • You can use gperf (website) to generate a perfect hash, which turns strings into integers. You'll have something like this:

    In your header file:

    enum {
        STR_VAR_TOKEN_e,
        STR_INT_e,
        STR_BOOL_e
    };
    int get_index(char *str);
    

    In your gperf file:

    struct entry;
    #include <string.h>
    #include "header.h"
    struct entry { char *name; int value; };
    %language=ANSI-C
    %struct-type
    %%
    VAR_TOKEN_e, STR_VAR_TOKEN_e
    INT_e, STR_INT_e
    BOOL_e, STR_BOOL_e
    %%
    int get_index(char *str)
    {
        struct entry *e = in_word_set(str, strlen(str));
        return e ? e->value : -1;
    }
    

    In your switch statement:

    switch (get_index(node->node_kind)) {
    case STR_VAR_TOKEN_e: ...
    ...
    }