Juan
Juan

Reputation: 532

Switch with strings

Somehow my switch statement goes through none of my cases, but shouldn't it go in one? (I am using https://stackoverflow.com/a/4014981/960086 as a reference).

There is no output, and application is blocked after.

#include <stdio.h>

#include <stdlib.h>

#define BADKEY -1
#define string1 1
#define string2 2
#define string3 3
#define string4 4
char *x = "string1";

typedef struct {char *key; int val; } t_symstruct;

static t_symstruct lookuptable[] = {
    { "string1", string1 }, { "string2", string2 }, { "string3", string3 }, { "string4", string4 }
};

#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))

int keyfromstring(char *key) {
    int i;
    for (i=0; i < NKEYS; i++) {
        t_symstruct *sym = lookuptable + i;
        printf("before: \n");
        if (strcmp(sym->key, key) == 0) { //creates the ERROR
            printf("inside: \n");
            return sym->val;
        }
        printf("after: \n");
    }
    return BADKEY;
}

void newFunction(char *uselessVariable) {
    printf("keyfromstring(x): %i \n", keyfromstring(x));
            switch(keyfromstring(x))      {
                case string1:
                   printf("string1\n");
                   break;
            case string2:
                   printf("string2\n");
                   break;
            case string3:
                   printf("string3\n");
                   break;
            case string4:
                   printf("string4\n");
                   break;
           case BADKEY:
                printf("Case: BADKEY \n");
                break;
        }
}

int main(int argc, char** argv) {
    newFunction(line);
    return (EXIT_SUCCESS);
}

Upvotes: 0

Views: 442

Answers (2)

Anish Ramaswamy
Anish Ramaswamy

Reputation: 2351

  • Your lookuptable[] has a space after "string1" which is inconsistent with the other entries. I have a feeling you didn't want this.
  • Your keyfromstring() is incrementing sym wrong (this causes a segfault). Replace with:

int keyfromstring(char *key)
{
    int i;
    for (i=0; i < NKEYS; i++) {
        t_symstruct *sym = lookuptable + i;
        if (strcmp(sym->key, key) == 0)
            return sym->val;
    }
    return BADKEY;
}

OR

int keyfromstring(char *key)
{
    int i;
    for (i=0; i < NKEYS; i++) {
        if (strcmp(lookuptable[i].key, key) == 0)
            return lookuptable[i].val;
    }
    return BADKEY;
}

  • Put your printf("Case: nothing happen\n"); inside a default.

Upvotes: 5

bash.d
bash.d

Reputation: 13207

You can't do it that way. switch works for integer (constants), and your strings aren't any of those. Besides, look here, for this topic has already been discussed.

Upvotes: -3

Related Questions