Reputation: 99
Why am I able to assign a function that returns an int with no parameters specified to a function pointer that returns an int but takes an int argument?
For example when I do:
int f()
{ return 0;}
int (*ptr)(int) = f;
the compiler gives me no warnings
Upvotes: 2
Views: 311
Reputation: 477512
In C, f
doesn't take "no arguments", but rather "any arguments"*. Say int f(void)
to declare "no arguments".
This is different from C++. Notably, C has separate notions of function "declaration" and function "prototype":
int f(); /* declaration -- f is still a mystery */
int f(int, double); /* prototype -- now we know how to call f */
int f(int n, double c) { return -1; } /* defintion -- now we can link */
*) As I said in the comment, "any arguments" is restricted to types that do not suffer default-promotion (in the same way as default-promotion happens to variadic arguments). That is, float
, all flavours of char
and of short int
, and also ...
, are not permissible in the actual function signature.
Upvotes: 5
Reputation: 28728
Which compiler do you use?
invalid conversion from
int (*)()' to int (*)(int)'
Error 1 error C2440: 'initializing' : cannot convert from 'int (__cdecl *)(void)' to 'int (__cdecl *)(int)'
Upvotes: 0