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(){
}
Functions are always in memory, but not on the stack. They are part of the code loaded with the rest of the program, and are put in a special read-only segment of memory.
When you call the function, then space for its local variables (including arguments) are reserved on the stack.