由网友(小猪仔)分享简介:此代码:#include #include int main(void){bool flag = true;printf("%s", "xxxzzz" + ( flag ? 3 : 0 ));return 0;}使用-std=c11 -pedantic编译会导致警告:...
此代码:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
bool flag = true;
printf("%s
", "xxxzzz" + ( flag ? 3 : 0 ));
return 0;
}
使用-std=c11 -pedantic
编译会导致警告:
main.c:7:27: warning: adding 'int' to a string does not append to the string
[-Wstring-plus-int]
printf("%s
", "xxxzzz" + ( flag ? 3 : 0 ));
~~~~~~~~~^~~~~~~~~~~~~~~~~~
main.c:7:27: note: use array indexing to silence this warning
printf("%s
", "xxxzzz" + ( flag ? 3 : 0 ));
^
& [ ]
1 warning generated.
但是,此代码:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
bool flag = true;
printf("%s
", ("xxxzzz") + ( flag ? 3 : 0 ));
return 0;
}
使用-std=c11 -pedantic
编译会导致没有警告。
为什么出现此警告?
()
重要吗?
P.S.GCC/MSVC在这两种情况下都不会生成警告。
推荐答案
警告只是因为代码不是惯用的(即不寻常地使用指针算法),来自其他语言的人可能希望RHS自动进行字符串转换以创建"xxxzzz3"
或"xxxzzz0"
。
它是编译器发现的代码模式,这些模式在其他语言中可能很常见,但在C中具有不同的、可能是意外的语义。它试图提供帮助并防止常见的错误。
在任何情况下,它建议使用数组索引语义可能是更好的解决方案,因为语义清晰,但使用括号显然具有抑制警告的相同效果。
相关推荐
最新文章