Search code examples
ccomputer-science

How to turn this ifs statement to switch statement. in C language


int op_type(const char *input, int op_pos)
{
    int category;

    if (input[op_pos] == '+')
        category = 1;

    if (input[op_pos] == '*')
        category = 2;

    if (input[op_pos] == '/')
        category = 3;

    if (input[op_pos] == '^')
        category = 4;

    return category;
}

This function will be used for doing basic math.


Solution

  • Theoretically the answer should be:

    int op_type(const char *input, int op_pos)
    {
        int category;
        switch (input[op_pos]){
            case '+':
                 category = 1;
                 break;
            case '*':
                 category = 2;
                 break;
            case '/':
                 category = 3;
                 break;
            case '^':
                 category = 4;
                 break;
        }
        return category;
    }
    

    Hope this answered your question.