I recently wrote code at night and made a mistake. I needed to write in the virtual memory of the process a pointer to the desired function. I did it like this:

uint64_t *some_mapped_memory = ...; some_mapped_memory[0] = reinterpret_cast<uint64_t>(myFunc); 

The error is that I did not put & in front of the function name. And not the pointer, but the function itself. However, this code worked just as expected.

Moreover, I later made a test:

 #include <cstdio> void f() {} int main() { void (*fnc1)() = f; void (*fnc2)() = &f; printf("%p %p\n", f, &f); return 0; } 

Not only did printf print two identical values, the code above also compiled without problems.

I googled a little, but found nothing about it. Honestly, there is no gcc or other compiler at hand, tested with visual c++ . What does the standard think about my code? Well, is it obliged to work on another compiler, or is only &f valid? And why does my development environment show that fnc1 and fnc2 are both void(*)() , but auto fnc3 = f is void() ?

In general, what I have shown is some kind of evil clever transformation described by the standard, or an evil clever transformation that can visual c++ ?

  • one
    This can be preceded by an address redundant set of parentheses. en.cppreference.com/w/cpp/language/overloaded_address - PetSerAl am
  • @PetSerAl that you dropped, rather describes the operations that can be performed with the name of the function. But why is this happening I found here . I thought about the same thing (implicit conversion of a function to a pointer to it). But it was still interesting how exactly the standard relates to this situation ... - selya

1 answer 1

The name of a function (not a member function!) Can always be converted to a function pointer, regardless of the presence of an ampersand in front of the function name. Draft C ++ 17 [conv.func]:

An lvalue of function type can be converted to a prvalue of type “pointer to T”. The result is a pointer to the function.

A little more about function pointers can be found in my article , although there are no references to the standard, since It is designed for the initial level.

  • Hmm, yet it is standardized ... But the question is: can it lead to consequences in any situation? - selya
  • @selya, “this” is what? Lack of ampersand? No, he can not. - ixSci
  • yeah Well, it seems like that. Marked the answer. Do you think it is better to put an ampersand? (Like a good tone of writing code, perhaps) - selya
  • @selya, I put, simply because it clearly expresses intent. - ixSci 2:43 pm