Pointer to a function. Another ad approach

When reading this (the answer is psychotic), I figured out how to call the type definition into a pointer to a function. But, thinking about typedefs, I experimented with them a bit and was able to also call functions:

typedef void func(unsigned char);
void test(unsigned char a);

int main()
{
    unsigned char b=0U;
    func *fp=&test;
    while(1)
    {
        fp(b);
        b++;
    }
}

void test(unsigned char a)
{
    printf("%d",a);
}

I don’t understand what is the difference between using function pointer syntax and this approach? Both seem to almost give the same functionality.

+1
source share
3 answers

Style

typedef void func_t (void);
...
funct_t* fp;

It is one of the clearest ways to declare function pointers. Clear as it is consistent with the rest of the pointer syntax for C.

This is equivalent to a little less readable

typedef void (*func_t)(void);
func_t fp;

This, in turn, is equivalent to much less readable

void (*fp)(void);

, :

1) void sort (func_t* callback);      // very clear and readable!
2) void sort (func_t callback);       // hmm what is this? passing by value?
3) void sort (void(*callback)(void)); // unreadable mess

, typedefs. .

+4

i.e.

func *fp = &test; // fp is a function pointer!

typedef ,

typedef void (*func)(unsigned char);
func fp = &test; // Notice, no '*' in the declaration?
+3

If you funchave been typedefed as a function pointer, then guide

func *fp=&test; 

will be

func fp=&test;
+1
source

Source: https://habr.com/ru/post/1624272/


All Articles