Pav*_*kin 0 c clang compiler-warnings c11
这段代码:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
bool flag = true;
printf("%s\n", "xxxzzz" + ( flag ? 3 : 0 ));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译时会-std=c11 -pedantic导致警告:
main.c:7:27: warning: adding 'int' to a string does not append to the string
[-Wstring-plus-int]
printf("%s\n", "xxxzzz" + ( flag ? 3 : 0 ));
~~~~~~~~~^~~~~~~~~~~~~~~~~~
main.c:7:27: note: use array indexing to silence this warning
printf("%s\n", "xxxzzz" + ( flag ? 3 : 0 ));
^
& [ ]
1 warning generated.
Run Code Online (Sandbox Code Playgroud)
然而,这段代码:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
bool flag = true;
printf("%s\n", ("xxxzzz") + ( flag ? 3 : 0 ));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译时-std=c11 -pedantic不会产生任何警告。
为什么会出现这个警告?
为什么会()这样呢?
PS gcc / msvc 在这两种情况下都不会生成警告。
该警告只是因为代码不符合惯用(即不寻常地使用指针算术),来自其他语言的人们可能期望 RHS 的自动字符串转换来创建"xxxzzz3"或"xxxzzz0"。
它是编译器发现在其他语言中可能常见但在 C 中具有不同且可能意外的语义的代码模式。它试图提供帮助并防止常见错误。
无论如何,就清晰的语义而言,它建议使用数组索引语义可能是更好的解决方案,但使用括号显然具有抑制警告的相同效果。