Search code examples
cswitch-statementenumerated

My switch statement is always returning the first case?


I'm having some trouble with this code. I'm pretty new to a switch statements and enumerated types so may be overextending a bit. I managed to work this to enter the switch statement, but it keeps returning the first case. Any ideas why?

#include <stdio.h>
#include <string.h>

enum express {ADD, SUB, AND, OR, XOR, SHL, SHR};
express m_express;

express switchint(char *str);

int main(){
    unsigned int n1=0x00;
    unsigned int n2=0x00;
    char action[5];
    printf("Enter an expression: ");
    scanf("%x, %s, %x", &n1, action, &n2);
    m_express=switchint(action);
    unsigned int result;
    switch(m_express){

        case ADD:
            printf("add works");
            break;
        case SUB:
            printf("SUB works");
            break;
        default:
            printf("Default");
            break;
     }
}

express switchint(char *str){
    if( strcmp(str, "add")){
        return ADD;
    }
    else if ( strcmp(str, "sub")){
       return SUB;
    }
    else if ( strcmp(str, "and")){
        return AND;
    }
    else if ( strcmp(str, "or")){
        return OR;
    }
    else if ( strcmp(str, "xor")){
        return XOR;
    }
    else if ( strcmp(str, "shl")){
        return SHL;
    }
    else {
        return SHR;
    }
}

I haven't written the rest of the switch cases I need yet. Any help solving this issue is greatly appreciated!


Solution

  • strcmp returns 0 if both strings are equal. You should rewrite your checks:

    if( !strcmp(str, "add")) 
    {
    }
    else if ( !strcmp(str, "sub")){
           return SUB;
    }