首页 > 解决方案 > 类型的大小与其无符号的等价物?

问题描述

该标准指定了算术整数类型可以保持的最小范围。但是,是否可以保证对于每个有符号整数,其无符号等效值具有相同的大小?

换句话说,是否总是如此:

sizeof(short) == sizeof(unsigned short)
sizeof(int) == sizeof(unsigned int)
sizeof(long) == sizeof(unsigned long)
sizeof(long long) == sizeof(unsigned long long)

?

标签: c++unsignedsigned

解决方案


(以下所有 ISO 标准参考参考N4659:2017 年 3 月 Kona 后工作草案/C++17 DIS


但是,是否可以保证对于每个有符号整数,其无符号等效值具有相同的大小?

是的。

来自[basic.fundamental]/3 [摘录,强调我的]:

[basic.fundamental]/3

对于每个标准有符号整数类型,都存在相应的(但不同的)标准无符号整数类型:“<code>unsigned char”、“<code>unsigned short int”、“<code>unsigned int”、“<code >unsigned long int”和“<code>unsigned long long int”,每一个都与对应的有符号整数类型占用相同的存储量和对齐要求;[...]


推荐阅读