Reputation: 2134
Consider the following code and output:
#include <iostream>
int Add(int a, int b) {
return a + b;
}
int Subtract(int a, int b) {
return a - b;
}
int main() {
int (*fn1)(int, int);
int (*fn2)(int, int);
fn1 = &Add;
fn2 = &Subtract;
std::cout << "fn1 = " << fn1 << "\n";
std::cout << "*fn1 = " << *fn1 << "\n";
std::cout << "fn2 = " << fn2 << "\n";
std::cout << "*fn2 = " << *fn2 << "\n";
}
Output:
fn1 = 1
*fn1 = 1
fn2 = 1
*fn2 = 1
As a pointer, I would expect fn1
and fn2
to be memory addresses, and I don't really know what to expect for *fn1
and *fn2
. According to Wikipedia, "a function pointer points to executable code within memory", but I don't see how "executable code within memory" corresponds with "1".
Upvotes: 0
Views: 71
Reputation: 213955
What are Function Pointers Ponting To?
It depends on what kind of function pointer it is. For non-member function pointer (as in your example), the pointer usually points to the actual code for the function (though on some architectures, such as PowerPC, it may point into a special "function descriptor" instead):
To examine that value, you should print it as void *
, and not as bool
(which is what you have done in your example).
std::cout << "fn1 = " << (void*)fn1 << std::endl;
Another way to examine it is using a debugger. For example, in GDB:
(gdb) p/a fn1
(gdb) p/a fn2
Upvotes: 3
Reputation: 477640
*fn1
is a function lvalue, and such a value decays to a pointer to that function in most circumstances, including when passed as a function call argument.
You can dereference the result of the decay to get another function lvalue, ad infinitum: *****fn1
, ***********fn1
, etc.
Upvotes: 3