I have a short program with which I am going to test the “infinite recursion”. However, I meet another tough question associated to function pointer...
the program is as follow:
#include <stdio.h>
int repeat(char (*func)(int, int), int a) {
func(a, a+1);
return repeat(func, a+1);
}
char f (int a , int b){
printf("%d\n", a);
//return (double)(a + b);
return 'c';
}
int main(int argc, char const *argv[])
{
repeat(&f, 1);
return 0;
}
As for me, I think the 'f' in “repeat(&f, 1)” has the type of “char *” and the 'func' in “int repeat(char (*func)(int, int), int a)” has the type of “char *”,too.
However, it seems strange. If I change “(char (*func)(int, int), int a) ” to “(char func(int, int), int a) ”, the compiler(testing in gcc and vc6) do not give any warnings and the running result is the same.
If I change “(char (*func)(int, int), int a) ” to “(double func(int, int), int a) ”, the compiler throws:
warning: incompatible pointer types passing 'char ()(int, int)' to parameter of type 'double ()(int, int)' [-Wincompatible-pointer-types] repeat(&f, 1);
It seems that the compiler treat “double (int, int)” and “double (*)(int, int)” the same stuff. In other words, If I change “(char (*func)(int, int), int a)” to “double (*func)(int, int)”, the compiler will throw the same message (I have tested it):
warning: incompatible pointer types passing 'char ()(int, int)' to parameter of type 'double ()(int, int)' [-Wincompatible-pointer-types] repeat(&f, 1);
God... Well, it is not the end. After that, I change the “repeat(&f, 1)” to “repeat(f, 1)” with other parts unchanged. That is, the whole program is:
#include <stdio.h>
int repeat(char (*func)(int, int), int a) {
func(a, a+1);
return repeat(func, a+1);
}
char f (int a , int b){
printf("%d\n", a);
//return (double)(a + b);
return 'c';
}
int main(int argc, char const *argv[])
{
repeat(f, 1);
return 0;
}
the compiler do not give any warnings and the running results are the same.
So I am confused that all of the following paris yields no warnings and correct results.
1 repeat(&f, 1) int repeat(char (*func)(int, int), int a)
2 repeat(&f, 1) int repeat(char func(int, int), int a)
3 repeat(f, 1) int repeat(char (*func)(int, int), int a)
4 repeat(f, 1) int repeat(char func(int, int), int a)
Of course the 'f' in “repeat(f, 1)” has the type of “char (int, int)”, and the 'func' in "int repeat(double (func)(int, int), int a)" has the type of “char ()(int, int)”.
You can infer this by changing “int repeat(char (*func)(int, int), int a) ” to “int repeat(double (*func)(int, int), int a) ” and check the warning message:
warning: incompatible pointer types passing 'char (int, int)' to parameter of type 'double ()(int, int)' [-Wincompatible-pointer-types] repeat(f, 1);*
Who can give some comments? I totally think that only the first of the four is correct regarding the type.