【问题标题】:Access a function pointer without parenthesis访问不带括号的函数指针
【发布时间】:2010-12-04 11:48:53
【问题描述】:

我有这个代码:

#include <stdio.h>

int getAns(void);
int num;

int main() 
{
    int (*current_ans)(void);
    current_ans = &getAns;
    // HERE
    printf("%d", current_ans());    

}

int getAns()
{
    return num + 3;
}

但是,是否有可能在 // HERE 点中有一些东西允许下一行是 printf("%d", current_ans);,它以迂回的方式访问 getAns()?

【问题讨论】:

  • 不完全是您想要的,但如果您不知道 - 您可以执行 int v = current_ans(); 然后将 v 传递给 printf。

标签: c pointers function macros parentheses


【解决方案1】:

不,因为 current_anscurrent_ans() 是不同的东西。没有括号,current_ansgetAns 都是函数指针,而有括号,它们是函数调用。如果您认为括号是通过执行代码来解除对指针的引用,那么本质上您所要求的是将指针和指针的内容视为同一对象。

【讨论】:

    【解决方案2】:

    我怀疑你不能,因为() 是告诉编译器这是一个函数调用所必需的。 但是,如果你真的想这样做,你可以这样做:

    #define current_ans current_ans()
    

    【讨论】:

      【解决方案3】:

      虽然我同意皮埃尔的回答,但

      #define current_ans current_ans()
      

      会使代码非常不可读

      【讨论】:

      • +1。实际上,放置该宏会使main 代码垃圾。
      【解决方案4】:

      “#define current_ans myRoundaboutFnName()”怎么样

      【讨论】:

        猜你喜欢
        • 2019-11-30
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 2021-06-20
        • 1970-01-01
        • 2020-11-25
        • 1970-01-01
        相关资源
        最近更新 更多