Take the following C / C ++ code:
#include <stdlib.h> int inc(int i) { return i+1; } // int→int, like abs() // baz is bool→(int→int) int (*baz(bool b))(int) { return b ? &abs : &inc; } int main() { int (*foo(bool))(int); // foo is &(bool→(int→int)) foo = baz; }
Trying to compile this (gcc or g ++) gives:
$ g++ test.cc test.cc: In function 'int main()': test.cc:9: error: assignment of function 'int (* foo(bool))(int)' test.cc:9: error: cannot convert 'int (*(bool))(int)' to 'int (*(bool))(int)' in assignment
Check for yourself: the two types that he claims that they cannot convert among themselves are exactly the same. Why does he claim that they are incompatible?
EDIT 1 . The problem disappears when using typedef (as recommended), for example:
int main() { typedef int (*int2int)(int); typedef int2int (*bool2_int2int)(bool); bool2_int2int foo; foo = baz; }
EDIT 2 : the compiler, of course, was right. The problem with my source code, as many have pointed out, is that foo in main() is a function declaration, not a function pointer. Consequently, the error in the assignment did not contradict the types, but assigned a function, which is impossible. The correct code is:
#include <stdlib.h> int inc(int i) { return i+1; } // int→int, like abs() // baz is bool→(int→int) int (*baz(bool b))(int) { return b ? &abs : &inc; } int main() { int (*(*foo)(bool))(int); // foo is &(bool→(int→int)) foo = &baz; }
source share