The following fails to compile on Windows 10 Pro 64-bit using MSVS 2017 with:
Error C2440 'initializing': cannot convert from 'overloaded-function' to 'char *(__cdecl *)(const char *,int)'
E0386 no instance of overloaded function "strchr" matches the required type FunctionPointers001
#include <stdio.h>
#include <string.h>
double cm_to_inches(double cm) {
return cm / 2.54;
}
// "strchr" is part of the C string handling (i.e., no need for declaration)
// See https://en.wikipedia.org/wiki/C_string_handling#Functionsint main(void) {
double (*func1)(double) = cm_to_inches;
char * (*func2)(constchar *, int) = strchr; // ERROR THIS LINE
printf("%f %s", func1(15.0), func2("Wikipedia", 'p'));
/* prints "5.905512 pedia" */
return 0;
}
constchar * strchr ( constchar * str, int character );
char * strchr ( char * str, int character );
You're trying to mix the signatures.
Your func2 pointer takes a const char * as the first argument, therefore it must return a const char *. Your prototype says it returns a char *. That doesn't match either of the two signatures.
The Wikipedia code is C code. As mbozzi said, if you''re going to compile a C program, use a C compiler.
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
char * (*func2)( char *, int ) = strchr; // LINE NOW COMPILES and program works
But, I assume this is bad practice and another method for doing this is better.
The better minimal change to turn that C program into a valid C++ program is to add, rather than remove, const: constchar * (*func2)(constchar *, int) = strchr;
it's still going to be an ugly little program, like most C ported to C++ with minimal change.