enum class - printf 打印出错误的值
enum class - printf prints wrong value
我有这个enum class
:
enum class myEnum : u8{
LEVEL_ERROR = 0,
LEVEL_WARN = 50,
LEVEL_DEBUG = 150,
};
有时我会使用它(不完全是这样,但就是这样):
myEnum instance = 42;
printf("My enum is now: %u", instance);
EDIT: 当然是这样用的: myEnum instance = (myEnum)42;
打印的值有时是 298
有时是 126657066
但永远不会是 42
。所以我注意到所有这些 "random" 数字都是我的值,但填充了 3 个字节的任何东西(堆栈?)- 42 = 0x2A
、298 = 0x12A
和 126657066 = 0x78CA22A
。我知道我的类型正在提升为 int 但如果是无符号变量类型,它应该用 3 个字节的“0”填充。那么为什么用垃圾填充?
您的类型没有升级到 int
。整数提升应用于枚举类型 的变量参数列表参数,如果 它们受整数提升影响 [expr.call]/12. The problem is that integer promotions only apply to unscoped enumerations [conv.prom]。您的 enum class
是范围枚举。因此,该值不会被提升,并且您对 printf
的调用由于参数类型与格式字符串中指定的类型不匹配而具有未定义的行为(如上面的注释中所述)。您将不得不显式地将值转换为您想要的整数类型,或者将您的 enum class
更改为无范围枚举…
我有这个enum class
:
enum class myEnum : u8{
LEVEL_ERROR = 0,
LEVEL_WARN = 50,
LEVEL_DEBUG = 150,
};
有时我会使用它(不完全是这样,但就是这样):
myEnum instance = 42;
printf("My enum is now: %u", instance);
EDIT: 当然是这样用的: myEnum instance = (myEnum)42;
打印的值有时是 298
有时是 126657066
但永远不会是 42
。所以我注意到所有这些 "random" 数字都是我的值,但填充了 3 个字节的任何东西(堆栈?)- 42 = 0x2A
、298 = 0x12A
和 126657066 = 0x78CA22A
。我知道我的类型正在提升为 int 但如果是无符号变量类型,它应该用 3 个字节的“0”填充。那么为什么用垃圾填充?
您的类型没有升级到 int
。整数提升应用于枚举类型 的变量参数列表参数,如果 它们受整数提升影响 [expr.call]/12. The problem is that integer promotions only apply to unscoped enumerations [conv.prom]。您的 enum class
是范围枚举。因此,该值不会被提升,并且您对 printf
的调用由于参数类型与格式字符串中指定的类型不匹配而具有未定义的行为(如上面的注释中所述)。您将不得不显式地将值转换为您想要的整数类型,或者将您的 enum class
更改为无范围枚举…