预期溢出但添加两个字节不会
Overflow expected but adding two bytes does not
更新
谁能解释一下将 uint8_t
提升为 int
的原因?这种行为的用例是什么?我可以阻止推广吗?
我有这些非常简单的代码片段,它们将两个整数类型相加并打印结果。我编译了那些 没有任何优化 和 g++ --std=c++11 main.cpp -o test
int main()
{
uint8_t a = 200, b = 100;
uint16_t result = (a + b);
printf("result is %d\n", result);
}
输出:
result is 300
我原以为 (a + b)
的计算结果为 44
,因为它们都是 8 位类型,应该会溢出。但是我得到了 300
.
的意外结果
如果我用 uint32_t
和 uint64_t
重新 运行 相同的测试,它会按预期溢出:
int main()
{
uint32_t a = UINT_MAX, b = UINT_MAX;
uint64_t result = (a + b);
printf("result is %ld\n", result);
}
输出:
result is 4294967294
现在我不知道为什么 uint8_t
与 uint32_t
受到不同对待。
小于 int 的整数类型在对其执行操作时被提升为 int
C++ 标准:
5.10
— Otherwise, the integral promotions (4.5) shall be performed on both
operands. Then the following rules shall be applied to the promoted
operands:
— If both operands have the same type, no further conversion
is needed.
4.5.1 积分促销
A prvalue of an integer type other than bool, char16_t, char32_t, or
wchar_t whose integer conversion rank (4.13) is less than the rank of
int can be converted to a prvalue of type int if int can represent all
the values of the source type; otherwise, the source prvalue can be
converted to a prvalue of type unsigned int.
最有可能的原因是:
3.9.1 基本类型
Plain ints have the natural size suggested by the architecture of the
execution environment; the other signed integer types are provided
to meet special needs.
更新
谁能解释一下将 uint8_t
提升为 int
的原因?这种行为的用例是什么?我可以阻止推广吗?
我有这些非常简单的代码片段,它们将两个整数类型相加并打印结果。我编译了那些 没有任何优化 和 g++ --std=c++11 main.cpp -o test
int main()
{
uint8_t a = 200, b = 100;
uint16_t result = (a + b);
printf("result is %d\n", result);
}
输出:
result is 300
我原以为 (a + b)
的计算结果为 44
,因为它们都是 8 位类型,应该会溢出。但是我得到了 300
.
如果我用 uint32_t
和 uint64_t
重新 运行 相同的测试,它会按预期溢出:
int main()
{
uint32_t a = UINT_MAX, b = UINT_MAX;
uint64_t result = (a + b);
printf("result is %ld\n", result);
}
输出:
result is 4294967294
现在我不知道为什么 uint8_t
与 uint32_t
受到不同对待。
小于 int 的整数类型在对其执行操作时被提升为 int
C++ 标准: 5.10
— Otherwise, the integral promotions (4.5) shall be performed on both operands. Then the following rules shall be applied to the promoted operands: — If both operands have the same type, no further conversion is needed.
4.5.1 积分促销
A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.
最有可能的原因是:
3.9.1 基本类型
Plain ints have the natural size suggested by the architecture of the execution environment; the other signed integer types are provided to meet special needs.