I have defined some functions and I print their address like this:
#include<iostream>
#include <string>
using std::cout;
std::string func()
{
return "hello world\n";
}
int func2(int n)
{
if (n==0)
{
cout << func2 << std::endl;
return 1;
}
cout << func2 << std::endl;
return n + func2(n - 1);
}
//================================================
int main()
{
int (*fun)(int) = func2;
cout << fun;
cout << std::endl << func2(3);
}
When I print the function's name (address) they all print 1
on my compiler (Mingw gcc 4.8 ).
Is it OK or it should differ?
When you use pass-by-pointer, a copy of the pointer is passed to the function. If you modify the pointer inside the called function, you only modify the copy of the pointer, but the original pointer remains unmodified and still points to the original variable.
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.
Modifying the value of a pointerWe can change the pointer's value in a code, but the downside is that the changes made also cause a change in the original variable.
A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.
It doesn't exist an overload of operator<<
for std::ostream
that takes a function pointer. Thus the operator<<(std::ostream&, bool)
overload is prefered. The address of a function is always evaluated to true
when converted to bool
. Thus, 1 is printed.
Alternatevely, if a function pointer is not larger than the size of a data pointer, you could cast your function pointer to a void*
via reinterpret_cast
and evoke the operator<<(std::ostream&, void*)
overload and thus get the actual address of the function printed.
int (*fun)(int) = func2;
std::cout << reinterpret_cast<void*>(fun) << std::endl;
Live Demo
However, as correctly Neil and M.M mentioned in the comments there's no standard conversion from a function pointer to a data pointer, and this could evoke undefined behaviour.
Alternatively, and in my humble opinion properly, you could format your function pointer as a char
array buffer and convert its address to a string in the following way:
unsigned char *p = reinterpret_cast<unsigned char*>(&func2);
std::stringstream ss;
ss << std::hex << std::setfill('0');
for(int i(sizeof(func2) - 1); i >= 0; --i) ss << std::setw(2)
<< static_cast<unsigned int>(p[i]);
std::cout << ss.str() << std::endl;
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With