c++ - 多字符常量警告

标签 c++ c casting compiler-warnings portability

为什么这是一个警告?我认为在很多情况下,使用多字符 int 常量而不是“无意义”数字或定义具有相同值的 const 变量会更清楚。当解析 wave/tiff/其他文件类型时,将读取值与一些 'EVAW'、'data' 等而不是它们对应的值进行比较会更清晰。

示例代码:

int waveHeader = 'EVAW';

为什么会出现警告?

最佳答案

According to the standard (§6.4.4.4/10)

The value of an integer character constant containing more than one character (e.g., 'ab'), [...] is implementation-defined.

long x = '\xde\xad\xbe\xef'; // yes, single quotes

这是有效的 ISO 9899:2011 C。它在带有 -Wallgcc 下编译时没有警告,并且带有 的“多字符字符常量”警告-迂腐

来自 Wikipedia :

Multi-character constants (e.g. 'xy') are valid, although rarely useful — they let one store several characters in an integer (e.g. 4 ASCII characters can fit in a 32-bit integer, 8 in a 64-bit one). Since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult.

为了可移植性,不要使用整数类型的多字符常量。

关于c++ - 多字符常量警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25875063/

相关文章:

c++ - 对 vector 使用二进制搜索。

c++ - const char [22 ]' to ' LPCWSTR'

在 C 中将 float 转换为二进制数并显示

mysql - 使用 C libmysqlclient 无法解释的 MySQL 行为

c# - 为什么我不能将 linq 的 Cast 与用户定义的转换一起使用,但我可以将它与 Select 调用一起使用?

java - 为什么将 Type[] 转换为 Class[] 会抛出 ClassCastException?

image-processing - 如何在 Julia 中将一些计算值(浮点)转换为 RGB 类型?

c++ - C++11 中 ConstExpr 对象中的可变成员

c - 如何在我的 gstreamer 中启用 httpsrc 插件?

c++ - 为什么一个完美的转发功能必须模板化?