指向函数的指针 - 一种不同的声明方法 [英] Pointer to a function - A different approach of declaring

查看:45
本文介绍了指向函数的指针 - 一种不同的声明方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读this(精神病患者给出的答案)时,我了解如何 typedef 和调用函数指针.但是在考虑了 typedef 之后,我对它们进行了一些试验,并且也能够以这种方式调用函数:

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.

推荐答案

风格

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

是声明函数指针最清晰的方法之一.清除,因为它与 C 的其余指针语法一致.

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

相当于可读性稍差

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

通常,将指针语法隐藏在 typedef 后面是个坏主意.函数指针也不例外.

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

这篇关于指向函数的指针 - 一种不同的声明方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆