1

I cannot understand how to print the address of a function in C++: My simple code is the following:

#include<iostream>

int my_fun () {
          return 5 ; 
} 


int main () {


int (*fp)() = my_fun ; 

std::cout << &fp <<std::endl ; 
std::cout<<my_fun<<std::endl ; 
printf("%p\n",my_fun) ; 
std::cout<<(int*)my_fun<<std::endl ; 
}

but I cant understand why the

std::cout<<my_fun<<std::endl ; 

is giving me the number 1 while (int*)my_fun is giving me the right address. Sorry if the question is trivial.

This is the output of the program:

0x7fffed0713b0
1
0x7ff14f7ca209
0x7ff14f7ca209
RIXS
  • 115
  • 5
  • In general, you can't, unless you write your own code to do it. In practice, casting the address to `(void*)` (or some other type of data pointer) works. The problem with that approach is that data pointers are not required to be the same size as code pointers; if code pointers are larger than data pointers, a data pointer (i.e., `void*`) can't represent all possible code pointer values, and you might get the same output for different function pointers. – Pete Becker Jun 24 '21 at 13:17
  • But I can cast to any type of data pointer ? Also I would like to know why each time I run the code the fist address I print is different ? – RIXS Jun 24 '21 at 13:41
  • 1
    @RIXS: You can cast any kind of **data** pointer to `void*`, but it's implementation-defined whether you can cast **function** pointers. As for the different values - your data will typically also be in different locations, so why should code be frozen? – MSalters Jun 24 '21 at 14:26

0 Answers0