How to use an array index as an operator?

后端 未结 4 1816
清酒与你
清酒与你 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:42

    I'd be tempted to use a ternary for this:

    a = 12 + (sign[1] == '-' ? -1 : +1) * 10;

    Of course this defaults to + but you could introduce earlier checks to guard against that.

    You could use this to form a macro:

    12 + SIGN(1) 10;

    with

    #define SIGN(s) (sign[(s)] == '-' ? -1 : +1) *

    which recovers the form of the expression in your question excepting the square brackets.

提交回复
热议问题