1

I am making a simple scheduler that executes functions contained in a FIFO queue.

Those functions have a same return type int, but have different number of int arguments.

I tried to implement it this way, but it does not seem to work. The compiler forbids conversion between int(*)() , int(*)(int), int(*)(int, int), or to any of those sort. (Arduino Sketch compiler)

Is there a way to solve this problem, or could you recommend a better way around? Thanks!

My code:

typedef int (*fnptr)(); // Tried this!

int foo(int var) {
    return 0;
}

int main() {
    fnptr fp = &foo; // error: invalid conversion from 
                     // 'int (*)(int)' to 'int (*)()' 
                     // [-fpermissive]
    return 0;
}
8
  • Did you try fnptr fp = foo;? Commented Jan 16, 2016 at 18:00
  • Also, please be aware, using a mismatched function pointer to call a function can invoke UB. Commented Jan 16, 2016 at 18:02
  • @SouravGhosh Yup, it throws the same error. 'fnptr fp = &foo()' also makes the same error. Commented Jan 16, 2016 at 18:04
  • I believe your code works in C89. C99 introduced the "limitation" of "remove implicit int". Commented Jan 16, 2016 at 18:14
  • @upoque i did not add the () Commented Jan 16, 2016 at 18:17

1 Answer 1

0

You can cast:

fnptr fp = reinterpret_cast<fnptr>(foo);

The ()s are the "function call operator", adding them makes no sense at all in this situation, it changes the expression from "take the address of this function" to "take the address of this function's return value".

Note that aboev I don't even include the &, this is because the name of a function acts pretty much like a function pointer so it's already an address.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.