Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are two function pointers to the same function always equal?

Does the C++ standard guarantee that two pointers to a function always compare equal? I understand that this will normally be true for non-inline functions. But if there is an inline function and a pointer to the function is created in two separate compilation units, will the linker merge the two instantiations, or is it allowed to emit duplicate functions?

If the answer to the above is "they are equal": Does this still hold if there is a common header with an inline function, and both the main program and a dynamically loaded plugin (shared object/DLL) create a pointer to the function?

like image 511
tbleher Avatar asked Oct 02 '13 09:10

tbleher


People also ask

Can you compare function pointers in C?

Two function pointers can be compared with the == and != operators, just like any other kind of pointers. We can also compare a function pointer to the NULL pointer using the == and !=

What are function pointers and the differences between normal function and function pointers?

1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. 2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers. 3) A function's name can also be used to get functions' address.

Can a pointer point to a function?

A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions.

What is the difference between pointer and function?

Function Pointers are pointers(like variable pointers) which point to the address of a function. They actually calling the underlying function when you dereference them like a function call does. The main advantage of a function pointer is that you can pass it to another function as a parameter for example ...


1 Answers

Section §5.10/1 of the C++11 standard says:

Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address

Two copies of the same inline function are still the same function. From an implementation point-of-view, the compiler will generate a copy of the function in each translation unit but the linker will then throw one of the copies away so only one is remaining.

By taking the address of a function you prevent it from being inlined (different from inline, which is more about avoiding violation of the One Definition Rule).

DLLs are outside the scope of the standard but only one copy of the function will remain in the binary image so getting the function address (e.g. GetProcAddress) from the DLL will get the same function pointer as code inside the DLL.

like image 122
Simple Avatar answered Sep 17 '22 16:09

Simple