How to use an array index as an operator?

后端 未结 4 1821
清酒与你
清酒与你 2021-01-21 14:17

How to use an array index as an operator?

Such that:

#include

main()
{
    char sign[]={\'+\',\'-\'};
    int a, b;
    a = 12 sign[1] 10         


        
4条回答
  •  庸人自扰
    2021-01-21 14:30

    The simplest is to use a switch statement or if-else chain.

    #include
    
    int main() {
        char sign[]={'+','-'};
        int a,b;
    
        switch (sign[1]) {
            case '+':
                a = 12 + 10;
                break;
    
            case '-':
                a = 12 - 10;
                break;
        }
    
        printf("%d",a);
    }
    

    If I was doing this, I'd probably end up moving some of the logic into a function though. Perhaps something like this:

    #include
    
    int perform_operation(char op, int lhs, int rhs) {
        switch (op) {
            case '+':
                return lhs + rhs;
    
            case '-':
                return lhs - rhs;
    
            default:
                return 0;
        }
    }
    
    int main() {
        char sign[]={'+','-'};
        int a = perform_operation(sign[1], 12, 10);
        printf("%d",a);
    }
    

提交回复
热议问题