gpt4 book ai didi

c++ - C++ R-Value 有大小吗?

转载 作者:行者123 更新时间:2023-12-01 14:18:17 25 4
gpt4 key购买 nike

让我们假设 int 变量可以容纳的最大数字是 10 。考虑以下情况:

main()
{
int r1 = 10;
int r2 = 1;

int x = r1 + r2;
}

根据我目前的一点知识, r1 + r2 表达式会在将该值复制到 x 之前创建一个临时变量来保存结果。

我想知道的是,因为最大的 x 可以容纳是 10 ,我知道(实际上是猜测)如果我打印 x ,我会得到 10 。但是 r1 + r2 呢?表示 r1 + r2 表达式结果的这个临时变量是否也包含 10 ?。

换句话说,这个临时变量也有它可以容纳的最大值吗?

这可能是一个菜鸟问题,我道歉。

请注意:

I asked this question based on what i thought what overflowing is. That is; i thought when a variable reach to a state where (let's say for an integer case), if i add one more integer to it's value it's gonna overflow. And i thought when that happens the maximum value it holds gonna stay the same regardless of me increasing it. But that's not the case apparently. The behaviour is undefined when overflow for most types. check @bolov's answer

最佳答案

有符号整数

计算大于最大值或小于有符号整数类型的最小值的值称为“溢出”,属于未定义行为。

例如。:

int a = std::numeric_limits<int>::max();
int b = 1;
a + b;

上面的程序有未定义的行为,因为 a + b 的类型是 int 并且计算的值会溢出。

§ 8 Expressions [expr]

§ 8.1 Preamble [expr.pre]

  1. If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.


无符号整数

无符号整数不会溢出,因为它们总是以模算术计算。
unsigned a = std::numeric_limits<unsigned>::max();
a + 1; // guaranteed to be 0

unsigned b = 0;
b - 1; // guaranteed to be std::numeric_limits<unsigned>::max();

§6.9.1 Fundamental types [basic.fundamental]

  1. Unsigned integers shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer 49

49) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

关于c++ - C++ R-Value 有大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62209351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com