当与const一起使用时,此函数指针的行为会有所不同?

问题描述 投票:0回答:1
#include <stdio.h> typedef int (*func_t)(int); int foo(int x) { return x * 2; } int main() { const func_t ptr = foo; // Works //const func_t *ptr = &foo; // Fails: why? printf("%d\n", ptr(5)); // Outputs 10 }

sissue:

行const

func_t ptr = foo;

效果很好。
,否则,不注重

const func_t *ptr = &foo;

导致汇编误差

error: invalid conversion from 'int (*)(int)' to 'const func_t*' {aka 'int (* const)(int)'}

为什么const
func_t *ptr = &foo;

失败,我该如何修复?


    

c compiler-errors constants function-pointers typedef
1个回答
0
投票
这是将指针隐藏在

typedef

不是一个好主意的原因之一。

const func_t ptr

使函数指针“ const”。也就是说,它等效于

int (* const func_t)(int);
&foo

给出一个指向函数的指针,

int (*)(int)

。您无法将其分配给指针到函数的指针,并且
const
与它无关。
但是,您可以这样做:
const func_t  ptr1 = foo;
const func_t* ptr2 = &ptr1;

ptr2

int (*const *)(int)
,这就是您接受的,这就是您得到的。

最佳练习是要摆脱

&ptr1
中的隐藏指针,因为这显然很混乱:
typedef
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.