I'm having trouble comprehending some C++ syntax when paired with function pointers and function declarations, specifically:
When we wish to declare a kind of function, we usually write something like:
I'm happy with typedef void(*functionPtr)(int);
FunctionPtr is now a type that represents a pointer to a function that returns void and takes an int as an argument.
We may put it to use as follows:
typedef void(*functionPtr)(int);
void function(int a){
std::cout << a << std::endl;
}
int main() {
functionPtr fun = function;
fun(5);
return 0;
}
And 5 are printed on a screen.
We have a pointer to function fun, which we assign to function - function, and we run this function using a pointer.
Cool.
Now, according to some books, function and pointer to function are treated similarly, so after declaring the function() function, whenever we say function, we mean both real function and pointer to function of the same type, so the following compiles and every instruction yields the same result (5 printed on a screen):
int main() {
functionPtr fun = function;
fun(5);
(*fun)(5);
(*function)(5);
function(5);
return 0;
}
So, as long as I can conceive that pointers to functions and functions are essentially the same, it's great with me.
Then I thought, since the pointer to function and the real function are the same, why can't I perform the following:
typedef void(functionPtr)(int); //removed *
void function(int a){
std::cout << a << std::endl;
}
int main() {
functionPtr fun = function;
fun(5);
return 0;
}
This gives me following error:
prog.cpp:12:14: warning: declaration of 'void fun(int)' has 'extern' and is initialized functionPtr fun = function;