2

The following is using a function pointer in C:

#include <stdio.h>
void bar1(int i){printf("bar1 %d\n", i+1);}
void bar2(int i){printf("bar2 %d\n", i+2);}
void foo(void (*func)(), int i) {func(i);};
int main() {
    foo(bar2, 0);
}

It compiles with $gcc main.c.

The following is my attempt to migrate it to C++:

#include <cstdio>
void bar1(int i){printf("bar1 %d\n", i+1);}
void bar2(int i){printf("bar2 %d\n", i+2);}
void foo(void (*func)(), int i) {func(i);};
int main() {
    foo(bar2, 0);
}

Trying to compile it, I get errors:

$ g++ main.cpp
main.cpp:7:39: error: too many arguments to function call, expected 0, have 1
void foo(void (*func)(), int i) {func(i);};
                                 ~~~~ ^
main.cpp:10:2: error: no matching function for call to 'foo'
        foo(bar2, 0);
        ^~~
main.cpp:7:6: note: candidate function not viable: no known conversion from 'void (int)' to 'void (*)()' for 1st argument
void foo(void (*func)(), int i) {func(i);};
     ^
2 errors generated.

How can I migrate C function pointers to C++?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 2
    You declare the argument to foo to be a pointer to function that doesn't take arguments. Fix that. – Mat Jul 08 '18 at 17:58
  • You mean it should be `void (*func)(int i)`, even in `C`? May I ask why `C` compiler don't ask me that? – KcFnMi Jul 08 '18 at 18:00
  • Probably related/possible dupe: https://stackoverflow.com/questions/51032/is-there-a-difference-between-foovoid-and-foo-in-c-or-c – UnholySheep Jul 08 '18 at 18:06
  • It is because in C function can not be overloaded. You may still want to compile with something like `-fstrict-prototypes` to ensure that function signature remains consistent everywhere. – user7860670 Jul 08 '18 at 18:06

1 Answers1

12

In C, void f() declares f to be function that takes an unspecified number of arguments and returns int. In C++ it declares f to be a function that takes no arguments and returns int. In C, if you want to write a function that takes no arguments you use void as the argument list: void f(void) declares a function that takes no arguments and returns nothing.

Unless you have a good reason to do otherwise, the way to write the code in the question is void foo(void (*func)(int), int i). That says that func is a pointer to a function that takes one argument of type int and returns void.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • 1
    Just for comparison: C's equivalent of the C++ function pointer: `void (*func)(` **void** `)` (for functions analogously, require explicit void parameter). – Aconcagua Jul 08 '18 at 18:10
  • @Aconcagua -- good point. I've edited my answer to mention `void` as an argument list in C. – Pete Becker Jul 08 '18 at 18:13