的typedef是如何工作的函数指针 [英] How typedef works for function pointers

查看:123
本文介绍了的typedef是如何工作的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可以从可怕的意外程序员病是患了,至少当谈到typedef和函数指针。所以,我一直在尝试用各种涉及这些分析的基础上所有的输出我得到的结果组合。

I think I may be suffering from the dreaded "accidental programmer" disease, at least when it comes to typedefs and function pointers. So I've been experimenting with all kinds of combinations involving these to analyse the results based on all the output I get.

但正如我一直在尝试不同的组合,而不是分析现在我只是失去了过程的结果。

But as I kept on trying different combinations, instead of analyzing the results I'm now just lost in process.

我希望你们会帮我找出这个烂摊子。

I'm hoping you guys will help me figure out this mess.

第一code例如

typedef void (print)(void);
void do_something (void) { printf("Hello World\n"); }

print *pr;
pr = &do_something;
pr(); // Hello World

二code例如

typedef void (print)(void);
void do_something (void) { printf("Hello World\n"); }

print *pr;
pr = do_something;
pr(); // Hello World

如何既高于code范例工作,就好像'和;'对函数名没有任何影响

How do both the above code examples work, it's as if '&' has no effect on function name

第三code例如

typedef void (print)(void);
void do_something (void) { printf("Hello World\n"); }

print pr;
pr = do_something; // compile error
pr = &do_something; // compile error
pr();

我希望上面的任务之一在这里工作,但该死的!我真不明白函数指针(也许是太类型定义)。

I was hoping one of the above assignments to work here but damn! I really don't understand function pointers (and maybe typedef too).

推荐答案

函数名称的地址和简单的函数名都意味着同样的事情,所以&安培; 有一个函数名没有影响。

The address of a function name and the plain function name both mean the same thing, so & has no effect on a function name.

类似地,使用函数指针时,多个解引用不是问题:

Similarly, when using function pointers, multiple dereferencing isn't a problem:

#include <stdio.h>
typedef void print(void);
static void dosomething(void) { printf("Hello World\n"); }

int main(void)
{
    print *f1 = dosomething;
    print *f2 = &dosomething;
    f2();
    (f1)();
    (*f1)();
    (**f2)();
    (***f1)();
    (****f2)();
    (*****f1)();
}

这下完全编译:

gcc -O3 -g -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
    -Wold-style-definition -std=c99 xx.c -o xx

我不主张多颗好作风;事实并非如此。它是奇怪,(是的,你可能会说的话)倒行逆施。一个是足够了(与一星主要是针对像我这样谁学会了用C编程前的水平说:这是可以通过一个指针调用函数时不使用(* pointer_to_function)(ARG1 ,ARG2)符号,你可以只写 pointer_to_function(ARG1,ARG2)如果你喜欢)。是的,这是怪异。没有,没有其他类型的(或类类型)表现出相同的行为,谢天谢地。

I would not claim that multiple stars is good style; it isn't. It is 'odd, and (yes, you may say it) perverse'. One is sufficient (and the one star is mainly for people like me who learned to program in C before the standard said "it is OK to call a function via a pointer without using the (*pointer_to_function)(arg1, arg2) notation; you can just write pointer_to_function(arg1, arg2) if you like"). Yes, it is weird. No, no other type (or class of types) exhibits the same behaviour, thank goodness.

这篇关于的typedef是如何工作的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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