gpt4 book ai didi

c - 使用 -Wwrite-strings 时在 GCC 5 中键入与自身不兼容的类型

转载 作者:太空狗 更新时间:2023-10-29 17:26:01 24 4
gpt4 key购买 nike

考虑:

char f(const char (*x)[4]);

void foo(void) {
typeof(*"FOO") x[4];
f(&x);
}

-Wwrite-strings编译:

gcc-5 -c gcc5.c  -Wwrite-strings

你得到:

gcc5.c: In function ‘foo’:
gcc5.c:5:7: warning: passing argument 1 of ‘f’ from incompatible pointer type [-Wincompatible-pointer-types]
f(&x);
^
gcc5.c:1:6: note: expected ‘const char (*)[4]’
but argument is of type ‘const char (*)[4]’
char f(const char (*x)[4]);
^

看起来像是 gcc 中的错误,除非我遗漏了什么?

注意:-Wwrite-strings改变文字串的类型:

When compiling C, give string constants the type "const char[length]"

最佳答案

对我来说,这确实是 gcc 5 中的一个错误。

gcc documentation

-Wwrite-strings

When compiling C, give string constants the type const char[length] so that copying the address of one into a non-const char * pointer produces a warning.

所以有了这个声明:

typeof(*"FOO") x[4];

-Wwrite-strings 存在时,&xconst char (*)[4] 类型。在标准 C 中,&xchar (*)[4] 类型。

这个小函数:

void foo(void) {
typeof(*"FOO") x[4];
printf("%d\n", __builtin_types_compatible_p(typeof(&x), const char (*)[4]));
printf("%d\n", __builtin_types_compatible_p(typeof(&x), char (*)[4]));
}

打印:

1
0

使用 gcc 5.3-Wwrite-strings。所以我们可以看到 gcc 5.3 正确地将 &x 识别为 const char (*)[4] 类型-Wwrite-strings

gcc 在调用具有 const char (*)[4] 参数的函数时应该接受参数 &x。不兼容类型的警告是恕我直言,然后是 gcc 中的错误。

(这个错误可能没有在以前版本的 gcc 中显示,只是因为 gcc 未能(另一个错误)将 &x 识别为const char (*)[4] with -Wwrite-strings 在以前的 gcc 版本中。我用 gcc 测试过4.9.2gcc-6-20151206。)

关于c - 使用 -Wwrite-strings 时在 GCC 5 中键入与自身不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34438459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com