I’ve tried searching a bit around SO, but I can’t find an answer to this question. Perhaps because I can’t put it in proper terms. What I want to know is how are functions represented in memory? Instructions must have some storage requirements and we can use function pointers to capture the their locations in memory… Could someone elaborate on this?
The most general notions, specific implementations are not important. And why doesn’t sizeof apply to functions? I am really curious about this, I apologize if my notions are flawed from the start (in other words, if I am thinking about it in a wrong way).
It depends on the language. For compiled languages, functions are represented in memory as machine code; you can generally get documentation for widely used processors from their manufacturers.
For C/C++, function pointers can be as simple as the address of the entry point to the function, which can be called directly with a single instruction. I believe this is typical for C/C++ implementations, but the specs do not guarantee it. In general, the type of a function pointer determines the calling convention of the function: what arguments it expects to find, and how it returns its results.
The actual code size of the function is not relevant to calling it —
sizeof(my_function_pointer)indicates the size of the function pointer, not the function. Note that even a raw function address may be represented differently from a data pointer (q.v., compilers targeting early Wintel segmented architectures, or embedded processors which may have completely different address spaces for code and data).For languages in which (unlike C) a function argument may refer to a closure, such a “pointer” would need to include or reference the closure context, as well as the entry point for the function.