Clang:<;字符串文字&>+<;返回int&>;表达式会导致令人困惑的警告:将';int';添加到字符串中不会追加到该字符串中 [英] clang: <string literal> + <expression returning int> leads to confusing warning: adding 'int' to a string does not append to the string
本文介绍了Clang:<;字符串文字&>+<;返回int&>;表达式会导致令人困惑的警告:将';int';添加到字符串中不会追加到该字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码:
#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中具有不同的、可能是意外的语义。它试图提供帮助并防止常见的错误。
在任何情况下,它建议使用数组索引语义可能是更好的解决方案,因为语义清晰,但使用括号显然具有抑制警告的相同效果。
这篇关于Clang:<;字符串文字&>+<;返回int&>;表达式会导致令人困惑的警告:将';int';添加到字符串中不会追加到该字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文