枚举超过了最大数字类型的大小
enums exceeding the size of the largest number type
我想完全理解C++编译器如何处理超过最大可能数的枚举,即同时包含-1
和UINT64_MAX
,即
enum A {
X = -1,
Y = UINT64_MAX
};
首先我认为编译器不会接受这个代码。事实上,当enum
被enum class
替换时,它并不编译,但上面的例子编译了。根据我们对底层类型的标准:
声明其基础类型不是固定的无范围枚举类型(在这种情况下,基础类型是实现定义的整数类型,可以表示所有枚举器值;除非枚举器的值不能容纳在int或无符号int中,否则此类型不大于int。如果枚举器列表为空,则基础类型就像枚举有一个值为0的枚举器一样)。(https://en.cppreference.com/w/cpp/language/enum)
但这对我的示例意味着什么?
我写了一个小样本程序来了解发生了什么:
#include <iostream>
#include <cstdint>
enum A {
X = -1,
XX = -1,
Y = UINT64_MAX
};
int main()
{
std::cout << "X unsigned: " << (uint64_t)(X) << ", signed: " << (int64_t)(X) << std::endl;
std::cout << "Y unsigned: " << (uint64_t)(Y) << ", signed: " << (int64_t)(Y) << std::endl;
std::cout << "(X == XX) == " << (X == XX) << std::endl;
std::cout << "(X == Y) == " << (X == Y) << std::endl;
}
输出为:
X unsigned: 18446744073709551615, signed: -1
Y unsigned: 18446744073709551615, signed: -1
(X == XX) == 1
(X == Y) == 0
现在我很困惑。显然,X和Y表示相同的数字,但它们仍然是可区分的,即比较X == Y
是假的(但X=XX
实际上是真的)。这里发生了什么?
我知道,更好的方法不是使用旧的enum
,而是使用新的enum class
。但enum
仍然被广泛使用,我想了解这里发生了什么。
您的编译器很可能使用128位有符号整数类型作为支持类型,并与C++标准兼容。
使用亲自查看
std::cout << sizeof(std::underlying_type<A>::type);
链接:https://ideone.com/z4K0rz,输出16。
您观察到的输出与将其缩小为64位无符号类型的转换一致。
您看到的是类型转换的影响,而不是enum
。您的输出取决于您如何投射值。
试试这个:它的输出与你的相同,没有enum
s。
#include <iostream>
#include <cstdint>
int main()
{
std::cout << "X unsigned: " << (uint64_t)(-1) << ", signed: " << (int64_t)(-1) << std::endl;
return 0;
}
输出为:
X unsigned: 18446744073709551615, signed: -1
相关文章:
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 你能在 c++ 中将不同的数字类型加在一起吗?
- 输出一个数字,该数字可能是三种类型之一
- 如何用不同的参数类型和数字回调函数
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- typeid.name 返回派生类类型之前的数字
- C++小数点后有 200 位数字的类型?
- 常量整数变量和数字的不同类型推导
- 检测<T>某些非数字类型 T 的 std::numeric::type 的特化
- 随机数字双重类型
- 当数字可能超出C++中特定数据类型的范围时如何处理异常?
- 为什么数字类型只有"to_string()"?
- 如何在数字大于类型 size_t 的最大数量时使用 std::bitset
- C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串
- 从 std::stringstream 读取uint8_t为数字类型
- 如何检查 stdin 中的数字是否小于给定类型的数字限制
- 创建一个带有限制的数字数据类型,一个介于 -10 和 10 之间的整数
- 无符号窄字符类型数字表示
- c++中对包含双精度类型数字的数组进行排序的最快方法是什么?