FCo
FCo

Reputation: 505

Function Pointers with Different Return Types C

I understand what function pointers are in C as well as how to use them. However, I do not know how to have one function pointer that can point to functions with different return types. Is this possible? I know how to use an array of function pointers, but I have only found examples of different parameters, not return types. (C: How can I use a single function pointer array for functions with variable parameter counts?) If an array would make more sense, can you provide an example of how to do this?

I have a switch/case statement to select the function that will be pointed to. This is then passed as an argument to another function. For example, I have listed some of the functions that I will need to implement below:

float* doFloatOps();
void goToSleep();
int* multiplication();

I need to have one function pointer that can be set to point to either of those. I think that I can only have one pointer due to the setup of the code. If you see a way to restructure this to make the function pointing easier, I would appreciate the input. The current structure of my code is like this:

switch(letter)
{
    case 'a':
    {
        functionPointer = &doFloatOps;
    }
    case 'b':
    {
        functionPointer = &goToSleep;
    }
     .......
}

void carryOutFunctions(functionPointer)
{
    while(....)
    {
        functionPointer;
    }
}

Please excuse any syntax errors above not pertaining to the function pointer problem.

So my main question is: how can I either have an array of function pointers with different return types or enable one function pointer to point to functions with different return types?

Upvotes: 4

Views: 3673

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

It's not possible, you can't have a function pointer that points to functions with different return types, because they would be of incompatible types. In this cases you can try returning void * and then handle the return value according to your needs.

Of course this requires you to be very careful when handling the returned data. One example of this technique is in the pthreads where you pass a function pointer to pthread_create() with the following type void (*)(void *).

In your case it should work if the functions return void *, and remember that void * is convertible to any pointer type without casting.

You could also use a union as a return type of course.

Upvotes: 4

Related Questions