关于看似兼容的函数指针赋值的编译器警告(const vs no-const)

标签 c

我遇到了一些我认为应该有效的有趣的事情。首先:

编译器/版本

$ gcc --version
gcc (Debian 4.7.2-5) 4.7.2

编译器选项和警告消息。

$ gcc -c warn.c -o warn.o
warn.c:11:5: warning: initialization from incompatible pointer type [enabled by default]
warn.c:11:5: warning: (near initialization for ‘foo.exec’) [enabled by default]

我想知道为什么“Foo()”与“exec”不兼容。 (添加评论以希望完全清晰)

typedef struct Thing
{
    void (*exec)(char *abc);
} Thing;

// ME: I don't mess with this.. I make const, K?
void Foo(const char *abc)
{
    (void) abc;
}

// GCC: LOL, nope! probably u messed up.
Thing foo = { Foo };

最佳答案

const char *char * 不同。

来自 C 标准 6.7.5.3(我强调):

15 For two function types to be compatible, both shall specify compatible return types. Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types. [...]

来自 C 标准 6.7.5.1(我强调):

2 For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.

注意:const 是一个限定符

关于关于看似兼容的函数指针赋值的编译器警告(const vs no-const),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18458702/

相关文章:

c - 我如何检查这种宏依赖性?

c - 填充 char* 数组时发生访问冲突

c - 如何使用文件结构?

c - 椭圆曲线密码学的 C 语言实现

c - 如何在 C 中增加指针(二维数组)

将字符输入转换为十进制输出——不懂

c - 如何访问 C 变量以进行内联汇编操作?

c - 在使用 Windows 7/8.1 和 Windows 10 的 FormatMessage 中的 LocalFree/HeapFree 之前,我是否应该查询操作系统?

将包含 12 位数字的 16 位数组转换为 8 位连续数组

java - 改进计算余数的递归