How can pointers to functions point to something that doesn't exist in memory yet? Why do prototypes have different addresses?

Posted by Kacy Raye on Stack Overflow See other posts from Stack Overflow or by Kacy Raye
Published on 2013-06-30T04:17:17Z Indexed on 2013/06/30 4:21 UTC
Read the original article Hit count: 128

To my knowledge, functions do not get added to the stack until run-time after they are called in the main function.

So how can a pointer to a function have a function's memory address if it doesn't exist in memory?

For example:

using namespace std;
#include <iostream>

void func() {
}  

int main() {
  void (*ptr)() = func; 
  cout << reinterpret_cast<void*>(ptr) << endl; //prints 0x8048644 even though func never gets added to the stack
}

Also, this next question is a little less important to me, so if you only know the answer to my first question, then that is fine. But anyway, why does the value of the pointer ( the memory address of the function ) differ when I declare a function prototype and implement the function after main?

In the first example, it printed out 0x8048644 no matter how many times I ran the program. In the next example, it printed out 0x8048680 no matter how many times I ran the program.

For example:

using namespace std;
#include <iostream>

void func();

int main() {
  void ( *ptr )() = func;
  cout << reinterpret_cast<void*>(ptr) << endl;
}

void func(){
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about memory