有符号整数溢出行为
Signed integer overflow behaviour
当添加两个理论结果大于 Int32.MaxValue
的正 Int32
值时,我可以指望溢出值总是负数吗?
我的意思是这样做是为了在不使用已检查上下文和异常处理的情况下检查溢出(如此处建议的:http://sandbox.mc.edu/~bennet/cs110/tc/orules.html),但这种行为是否得到保证?
到目前为止我读到的是 C# 定义的行为中有符号整数溢出 (Is C#/.NET signed integer overflow behavior defined?)(与 C/C++ 形成对比)并且 Int32
是二元补码所以我会感谢比我更了解这个主题的人来验证这一点。
更新
引自 link 1:
The rules for detecting overflow in a two's complement sum are simple:
- If the sum of two positive numbers yields a negative result, the sum has overflowed.
- If the sum of two negative numbers yields a positive result, the sum has overflowed.
- Otherwise, the sum has not overflowed.
规则 #2 来自
http://sandbox.mc.edu/~bennet/cs110/tc/orules.html
不正确
- If the sum of two negative numbers yields a positive result, the sum has overflowed.
反例:
int a = int.MinValue;
int b = int.MinValue;
unchecked {
// 0
Console.Write(a + b);
}
但是,可以简单地修改规则
- If the sum of two negative numbers yields a non-negative result, the sum has overflowed.
关于规则 #1
- If the sum of two positive numbers yields a negative result, the sum has overflowed.
正确一个
不,你不能。
您已经谈到了 checked
上下文,其中您知道溢出会导致抛出异常。但是,您似乎假设缺少 checked
关键字表示您处于 unchecked
上下文中。不一定是这样。 checked
和 unchecked
均未指定时的默认上下文是可配置的,在共享相同源文件的多个项目中可以不同,甚至可以在同一项目的不同配置之间不同。
如果您希望整数溢出换行,请显式使用 unchecked
关键字。
当添加两个理论结果大于 Int32.MaxValue
的正 Int32
值时,我可以指望溢出值总是负数吗?
我的意思是这样做是为了在不使用已检查上下文和异常处理的情况下检查溢出(如此处建议的:http://sandbox.mc.edu/~bennet/cs110/tc/orules.html),但这种行为是否得到保证?
到目前为止我读到的是 C# 定义的行为中有符号整数溢出 (Is C#/.NET signed integer overflow behavior defined?)(与 C/C++ 形成对比)并且 Int32
是二元补码所以我会感谢比我更了解这个主题的人来验证这一点。
更新
引自 link 1:
The rules for detecting overflow in a two's complement sum are simple:
- If the sum of two positive numbers yields a negative result, the sum has overflowed.
- If the sum of two negative numbers yields a positive result, the sum has overflowed.
- Otherwise, the sum has not overflowed.
规则 #2 来自
http://sandbox.mc.edu/~bennet/cs110/tc/orules.html
不正确
- If the sum of two negative numbers yields a positive result, the sum has overflowed.
反例:
int a = int.MinValue;
int b = int.MinValue;
unchecked {
// 0
Console.Write(a + b);
}
但是,可以简单地修改规则
- If the sum of two negative numbers yields a non-negative result, the sum has overflowed.
关于规则 #1
- If the sum of two positive numbers yields a negative result, the sum has overflowed.
正确一个
不,你不能。
您已经谈到了 checked
上下文,其中您知道溢出会导致抛出异常。但是,您似乎假设缺少 checked
关键字表示您处于 unchecked
上下文中。不一定是这样。 checked
和 unchecked
均未指定时的默认上下文是可配置的,在共享相同源文件的多个项目中可以不同,甚至可以在同一项目的不同配置之间不同。
如果您希望整数溢出换行,请显式使用 unchecked
关键字。