C ++ function pointer not changed

I defined some functions and print their address as follows:

#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 name (address), they all print 1 in my compiler (Mingw gcc 4.8).

Is everything alright or should it be different?

+6
source share
2 answers

You do not print the address, because now it is converted to a boolean value.

But you can do it, for example. this is:

 std::cout << reinterpret_cast<unsigned long long int *>(func2) << std::endl; 

You will now receive the actual address.

0
source

There is no operator<< overload for std::ostream that takes a function pointer. Thus, operator<<(std::ostream&, bool) overload operator<<(std::ostream&, bool) preferred. The function address is always evaluated to true when converting to bool . So 1 is printed.

Alternatively, if the function pointer is not larger than the size of the data pointer, you can specify the pointer to void* via reinterpret_cast and cause operator<<(std::ostream&, void*) to overload operator<<(std::ostream&, void*) and thus get the actual address of the printed function.

 int (*fun)(int) = func2; std::cout << reinterpret_cast<void*>(fun) << std::endl; 

Live demo

However, neither Neil nor MM in the comments mention the standard conversion from pointer to data pointer, and this can cause undefined behavior.

Alternatively, and in my humble opinion, you can format the function pointer as a char array buffer and convert its address to a string as follows:

 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

+3
source

All Articles