c++macrosfunction-pointers

How to use macro as function pointer?


How can I use macros as function pointers? I have no idea to solve this. I created a sketch (doesn't work, full of syntax errors) to show what I try to accomplish. Please help!

#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
#define D1_OUT(x) (x*1024) //I want to use this for Pin1 calculation

struct Pin {
  CalcMethod *calcMethod; //int methodName(int x) { return MACRO(x); }

  Pin(CalcMethod *calcMethodParam) {
    calcMethod = calcMethodParam;
  }

  int calc(int x) {
    return calcMethod(x);
  }
};

#define PIN_COUNT 2
Pin *pins[PIN_COUNT];

void start() {
    pins[0] = new Pin(D0_OUT); //use the D0_OUT macro to calculate
    pins[1] = new Pin(D1_OUT); //use the D1_OUT macro to calculate
    int pin0CalcResult=pins[0]->calc(5); // =5/1024*100
    int pin1CalcResult=pins[1]->calc(6); // =6*1024
}

Solution

  • Macros are handled by the preprocessor. They don't exist in the compiled code, therefore there is no pointer.

    There is one rule you should follow in modern code and that rule is "don't use macros for furnctions". Macros for functions are a relict that still has some good uses but they are very rare.

    Just declare a normal function

    int do_out(int x) {
        return x / 1024 * 100;
    }
    

    Also see "static const" vs "#define" vs "enum"