How to use an array index as an operator?

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

    You could use function pointers:

    //function:
    int addInt(int a, int b) {
        return a+b;
    }
    
    //define the pointer:
    int (*functionPtr)(int,int);
    
    main ()
    {
      functionPtr sign[5];
      sign[0] = &addInt;
    
       int a = 5, b = 8;
      //...
      int sum = sign[0](a,b);
      printf("%d", sum);
      return 0;
    }
    

    It's a little bit more complicated, and in most simple cases, you would want to use a switch statement to call different functions, but this is a very useful method when dealing with larger, more complex cases.

    An example of when I've used arrays of function pointers like this was when developing an image processing application, with vendors providing the algorithms for some pretty special processing.
    Their code was proprietry though, and so while we could attain dlls containing functions that could do the processing, we couldn't build it into our code. As any number of these dlls may be required, and we wanted the ability to add-remove functionality without re-compiling the entire system, we needed to be able to read the dlls and manage them. We used a method like above for doing this.

提交回复
热议问题