Function-to-function-pointer “decay”

前端 未结 4 2053
傲寒
傲寒 2020-11-30 14:48

As we know a parameter that looks like void() will be rewritten as void(*)(). This is similar to array-to-pointer decay where int[] be

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 15:34

    When it's about data types, functions are not first class citizens in C and C++ (the question is about C++ but the behaviour is inherited from C). They are code, not data and they cannot be copied, passed as arguments to functions or returned by functions (but all these can happen to pointers to functions.)

    This is why a function name is treated like a pointer to that function and not like the function body itself.

    The possibility to use a function (name) instead of a pointer to the function is just a courtesy the language makes to the programmer, and not a "decay".

    The same for arrays: they are not copied, not passed as function arguments and not returned by functions. The address of their first element is used instead (copied, passed as function argument or returned by functions). This is why the array name can be used instead of the address of its first element and again, this is just a way to write less (and less obfuscated) code.

    For the compiler, a function is a block of memory (that contains code to be executed at some time) that does not move and is identified by its address, i.e. the pointer to the function. An array is also a block of data that does not move and is identified by its address (which is also the address of its first element). Again, this is a pointer.

    The concepts of function and array at higher levels (C, C++) are translated by the compiler to primitive values (pointers) that are understood by the lower levels (assembler, machine code).

提交回复
热议问题