Background
So this is what happens when you spend a few years writing Haskell then go back to bare metal C code:
Question
Is it possible for a function to have as its return type a pointer that is the same typs as the function itself? Is so, what is the syntax?
Is the name of the function in scope within the function body? or can I get the address of the function that is currently executing?
E.g.
void foo() {
callmeback(&foo); // is this legal
}
Why would you want to do this?
I've got a state machine that handles user input fro some very limited controls which means that the two input operations have to serve several different modes. I'm refactoring my spaghetti code full of switch statements and globals into something a bit more maintainable. If I were working in Haskell I would call the current mode function with the user input and have it return the a function to call with the subsequent input -- either itself or the handler for a new mode. I started to do this in C and realized that I have no clue how to write the type of the handler function. If this doesn't work out I'll simply set a global variable with the next handler and move on with life, but I just had to ask if it could be done the same way I would in a functional language.
For those that are curious, this is all running on an ESP32, a more capable processor but similar to an what come with and Arduino.
Yes, it is possible to return a function pointer to itself in C.
The return type you are looking for is a void pointer void*
And yes, the name of the function is also visible within its body in C. Things like recursion wouldn't have been possible if this wasn't the case.
Here is some code for illustration:
#include <stdio.h>
void* demo() // See the usage of void pointer
{
printf("This function returns a pointer to itself");
return &demo;
// return demo is also fine
// don't return demo(), that would be recursion!
}
int main()
{
// Syntax
void (*demoPtr)() = demo();
// Test if it worked
demoPtr(); // There's no problem in ignoring the return value
return 0;
}
Output:
This function returns a pointer to itself
This function returns a pointer to itself
Edit:
After reading the second part of your question which mentions your need to this, I think you may be looking for recursion or callback. If so then you can clarify it in the comments and I'll edit my answer accordingly.