Function pointer to __attribute__((const)) function?

让人想犯罪 __ 提交于 2019-12-05 01:22:43
typedef void (*t_const_function)(void) __attribute__((const));

static __attribute__((const)) void A(void) {
}

static void B(void) {
}

int main(int argc, const char* argv[]) {
    t_const_function a = A;

    // warning: initialization makes qualified
    // function pointer from unqualified:
    t_const_function b = B;

    return 0;
}

Or just:

__attribute__((const)) void(*a)(void) = A;

Although this is not quite the answer to your question, you probably want to know this:

You can't in the general case expect the compiler to perform the optimization you expect here. The compiler cannot in the general case do the alias analysis necessary to know that multiple uses of a function pointer correspond to the same function.

A function call in between two invocations of the function through the pointer could, in the general case, alter the pointer contents, thus causing the invoked function to be different in the second call.

Because of the nature of C, doing proper alias analysis is often intractable, and this sort of optimization is thus not likely to happen.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!