0

How to return an void (*)(void) variable from a function? More precisely how to mark the return type?

???? getFunc(){
        void (*pt2Func)(void) = ...;
        return pt2Func;
}

void main(){
     void (*myFunc)(void) = getFunc();
     myFunc();
}
alex-rudenkiy
  • 125
  • 1
  • 8

1 Answers1

2

The most readable approach is via a type alias:

using VoidFct = void (*)(void);

VoidFct getFunc(){
   return &f;
}

where the function to which a pointer is passed could be

#include <cstdio>

void f() {
   std::puts("laksjdf");
}

and the client could would be

VoidFct g = getFunc();

g();
lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 1
    Or, if one doesn't want to hide pointers with type aliases: `using VoidFct = void(); VoidFct* getFunc();`. – eerorika Apr 18 '19 at 09:46
  • @eerorika That's a good point. Reminds me of the fact that I usually feel uncomfortable when reading `auto var = getPointer()` instead of `auto *var = getPointer()`. – lubgr Apr 18 '19 at 09:50