0

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!

Benjamin M
  • 11
  • 1

3 Answers3

4

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

if( !strcmp(str, "add")) 
{
}
else if ( !strcmp(str, "sub")){
       return SUB;
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • This turned out to be half the issue. My scanf statement foolishly used commas also. Does this mean !strcmp(...) and strcmp(...)==0 work the same way? – Benjamin M Jul 30 '17 at 23:03
2

strcmp returns 0 when both strings are equal. So your comparison in your switchint function should be:

if(!strcmp(str, "add")) { ... }

Same goes for the other comparisons.

CRoemheld
  • 889
  • 7
  • 26
0

According to the description of the function in the C Standard (7.23.4.2 The strcmp function)

3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

So you should write at least like

express switchint( const char *str){
                   ^^^^^
    if( strcmp(str, "add") == 0 ){
        return ADD;
    }
    else if ( strcmp(str, "sub") == 0 ){
       return SUB;
    }
    // and so on
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335