为什么int32.maxvalue + 1溢出长时间? [英] Why does int32.maxvalue + 1 overflow a long?

查看:164
本文介绍了为什么int32.maxvalue + 1溢出长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你把下面的代码在.NET 4.5的应用程序:

If you put the following code in a .NET 4.5 application:

public const long MAXIMUM_RANGE_MAGNITUDE = int.MaxValue + 1;

一个编译器错误产生指出的操作在检查模式下编译时溢出。我知道,我可以把这个在选中块和被罚款,但我的问题是为什么错误出现在首位?显然,长的可以容纳一个INT的最大值加1。

A compiler error is generated stating "The operation overflows at compile time in checked mode". I know that I could put this in an "unchecked" block and be fine, but my question is why does the error appear in the first place? Clearly a long can hold a int's max value plus one.

请注意,使用的Int32和Int64的,而不是长期和INT似乎并没有帮助。

Note that using Int32 and Int64 instead of long and int does not seem to help.

推荐答案

这是因为在分配的右手边的计算是在整数类型而完成的。而且它的四溢整数

It is because the calculations on the right hand side of assignment is being done in integer type. And it is overflowing integer

您可以修复使用:

public const long MAXIMUM_RANGE_MAGNITUDE = int.MaxValue + (long)1; // or 1L



通过浇铸操作数中的至少一个长

By casting at least one of the operand to long

你在C#规范中指定的错误的原因。

The reason you get the error is specified in C# specifications.

查看 C#规范第4.1节。 5(整型)

See C# Specification Section 4.1.5 (Integral types)

有关二元+, - ,*,/,%,&安培; !^,|,= =,=,>,<,> =,和< =
运营商,操作数转换为类型T,其中T为int的第一
,UINT ,long和ulong 一个可以完全表示两个操作数的所有可能的
值。
的操作使用类型T的
精度进行,而结果的类型是T(或布尔为
关系运算符)。它不允许一个操作数为
型长,另一个是与二元运算ulong类型。

For the binary +, –, *, /, %, &, ^, |, ==, !=, >, <, >=, and <= operators, the operands are converted to type T, where T is the first of int, uint, long, and ulong that can fully represent all possible values of both operands. The operation is then performed using the precision of type T, and the type of the result is T (or bool for the relational operators). It is not permitted for one operand to be of type long and the other to be of type ulong with the binary operators.

在您的情况下,由于增加了两个操作数可在<$ C C> INT 因此,计算在整数类型来完成的。明确铸造操作之一将导致结果,因此没有溢出错误。

In your case since both operands of addition can be represented in int therefore the calculation is done in integer type. Explicitly casting one of the operand to long would result in long result and thus no overflow error.

这篇关于为什么int32.maxvalue + 1溢出长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆