MAO-EYE 2010-11-28 04:50 采纳率: 100%
浏览 249
已采纳

函数指针?

I'm learning how to dynamically load DLL's but what I don't understand is this line

typedef void (*FunctionFunc)();

I have a few questions. If someone is able answer them I would be grateful.

  1. Why is typedef used?
  2. The syntax looks odd; after void should there not be a function name or something? It looks like an anonymous function.
  3. Is a function pointer created to store the memory address of a function?

So I'm confused at the moment; can you clarify things for me?

转载于:https://stackoverflow.com/questions/4295432/typedef-function-pointer

  • 写回答

5条回答 默认 最新

  • 关注

    typedef is a language construct that associates a name to a type.
    You use it the same way you would use the original type, for instance

      typedef int myinteger;
      typedef char *mystring;
      typedef void (*myfunc)();
    

    using them like

      myinteger i;   // is equivalent to    int i;
      mystring s;    // is the same as      char *s;
      myfunc f;      // compile equally as  void (*f)();
    

    As you can see, you could just replace the typedefed name with its definition given above.

    The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

    The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

    To answer your three questions

    • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

    • The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

    • Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

    Example:

    typedef int (*t_somefunc)(int,int);
    
    int product(int u, int v) {
      return u*v;
    }
    
    t_somefunc afunc = &product;
    ...
    int x2 = (*afunc)(123, 456); // call product() to calculate 123*456
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图