多字符持续警告
为什么这是一个警告?我认为在很多情况下,使用多字符 int 常量而不是“无意义”的数字或定义具有相同值的 const 变量会更清楚。当解析wave/tiff/其他文件类型时,将读取的值与一些“EVAW”、“数据”等而不是其相应的值进行比较会更清楚。
示例代码:
int waveHeader = 'EVAW';
为什么会发出警告?
Why is this a warning? I think there are many cases when is more clear to use multi-char int constants instead of "no meaning" numbers or instead of defining const variables with same value. When parsing wave/tiff/other file types is more clear to compare the read values with some 'EVAW', 'data', etc instead of their corresponding values.
Sample code:
int waveHeader = 'EVAW';
Why does this give a warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
根据标准 (§6.4.4.4/ 10)
这是有效的 ISO 9899:2011 C。它在使用
-Wall
的gcc
下编译时没有警告,使用-pedantic< 则出现“多字符字符常量”警告。 /代码>。
来自维基百科:
为了可移植性,不要使用具有整型的多字符常量。
According to the standard (§6.4.4.4/10)
This is valid ISO 9899:2011 C. It compiles without warning under
gcc
with-Wall
, and a “multi-character character constant” warning with-pedantic
.From Wikipedia:
For portability sake, don't use multi-character constants with integral types.
此警告对于那些在应该编写
"test"
的地方错误地编写'test'
的程序员很有用。这种情况比真正需要多字符 int 常量的程序员更常见。
This warning is useful for programmers that would mistakenly write
'test'
where they should have written"test"
.This happen much more often than programmers that do actually want multi-char int constants.
如果您很高兴知道自己在做什么并且可以接受可移植性问题,例如在 GCC 上,您可以禁用命令行上的警告:
我将其用于我自己的应用程序,以处理类似的 AVI 和 MP4 文件头原因给你。
If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:
I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.
即使您愿意查找您的实现定义的行为,多字符常量仍然会随字节顺序而变化。
最好使用 (POD) struct { char[4] }; ...然后使用像“WAVE”_4cc 这样的 UDL 轻松构造该类的实例
Even if you're willing to look up what behavior your implementation defines, multi-character constants will still vary with endianness.
Better to use a (POD) struct { char[4] }; ... and then use a UDL like "WAVE"_4cc to easily construct instances of that class
@leftaroundabout 在上面的评论中提到了最简单的 C/C++ 任何编译器/标准兼容解决方案:
或者更具体一点:
还有一个解决方案,自 C99 以来也符合 C/C++ 编译器/标准(clang++ 除外,其中 有一个已知错误):
这里匿名联合用于为所需的数字结果提供一个漂亮的符号名称,“abcd”字符串用于初始化 复合文字 (C99)。
Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:
Or a bit more specific:
One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):
Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).
如果您想禁用此警告,请务必了解 GCC 和 Clang 中有两个相关的警告参数: GCC 编译器选项 -wno-四字符常量和 -wno-multichar
If you want to disable this warning it is important to know that there are two related warning parameters in GCC and Clang: GCC Compiler options -wno-four-char-constants and -wno-multichar