If I store a pointer to a function, and then at some later point during my program's execution, compare it to the address of the same function, are the two addresses guaranteed to be equal.
E.g.
int foo(void){return 0;}
int (*foo_p)(void) = &foo;
assert(foo_p == &foo);
In the above code is the assertion always guaranteed to succeed? Are there any circumstances under which the address of a function can change?
Address of a function in C or C++ We all know that code of every function resides in memory and so every function has an address like all others variables in the program. We can get the address of a function by just writing the function's name without parentheses.
Yes, they will change. Write a program that outputs the memory address of a few variables and run it a few times.
The address is the memory location where the entity is stored. Every block of code in the program has its own memory location in the program. Which means like any variable or object methods and functions also have memory address.
As we know that we can create a pointer of any data type such as int, char, float, we can also create a pointer pointing to a function. The code of a function always resides in memory, which means that the function has some address. We can get the address of memory by using the function pointer.
Per 6.5.9:
Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.
(Boldface added for emphasis.)
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