Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

c - Pointer to a function - A different approach of declaring

While reading this (the answer given by psychotic), I understood how to typedef and call a function pointer. But after thinking about typedefs I experimented with them a little and was able to call functions this way also:

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 get what is the the difference between using the function pointer syntax and this approach? Both seem to almost yield the same functionality.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The style

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

Is one of the clearest ways to declare function pointers. Clear because it is consistent with the rest of the pointer syntax of C.

It is equivalent to the slightly less readable

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

Which in turn is equivalent to the much less readable

void (*fp)(void);

The advantage of the first style becomes obvious when you pass these as parameters to a function:

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

Generally, it is a bad idea to hide the pointer syntax behind typedefs. Function pointers are no exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...