In depth analysis of function Pointers and return function Pointers
- 2020-04-02 01:12:00
- OfStack
Take a look at the following two codes:
1: from the stl-sgi source code
<
Stl_alloc. H
>
static void (*__set_malloc_handler(void (*__f)()))()
{
void (*__old)()=__malloc_alloc_oom_handler;
__malloc_alloc_oom_handler=__f;
return (__old);
}
2: under Linux < Sginal. H >
void (*signal (int sig_num, void (*handler)(int))) (int)
As a C/C++ master may see it, the following analysis, analysis method adopted from the inside out of the analysis method
The analysis of example 1 is as follows:
1) the innermost void (*_f)() indicates that _f is a pointer, combining with the right (), indicating that it is a function, combining with the leftmost void, indicating that it is a function pointer.
2) define void (*_f)() with typedef to facilitate the following analysis
Typedef void * F () ()
3) then the above code can be changed into the following form
The Static void (* __set_malloc_handler (F (F)) ()
4) then analyze from the inside out the function with () to show that the function is a function with the parameter type F F, and then combine with the * on the left to show that the function returns a pointer type, i.e. static void (*)(), so it is a function pointer
5) to sum up, the code function named with the function name of "s _malloc_handler" accepts a function pointer with null return value and null parameter as the parameter, and finally returns a function pointer with null return value and parameter, which is very convoluted :)
The analysis for example 2 is as follows
1) from the inside out inside is void (* handler)(int) looking at column 1, it is easy to know that this is a function pointer, return value is null, parameter is null
2) to void (*handler)(int) macro definition, to facilitate understanding
Typedef void * (Handle) (int)
3) so the function becomes void (signal(intsig_num,Handler))(int)
Signal (int sig_num,Handlerhandler) is a function with two parameters, the return value is *, is a pointer, return value is void(*)(int) is also a Handler type of function pointer
5) to sum up, the function name of code 2 is signal, which takes two arguments and returns a function pointer of Handler type.
The analysis of other code is similar, as shown in the following examples:
1:void *(*(*f)(int))[10];
Analysis of the following (*(*f)(int)->void *(*)[10]
2:void *(*f)(int)[10]
Analysis of the following (*f)(int)->void *[10]
And then there are some that are basically similar transformations