是C#/。.NET有符号整数溢出行为定义吗? [英] Is C#/.NET signed integer overflow behavior defined?

查看:264
本文介绍了是C#/。.NET有符号整数溢出行为定义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在unchecked上下文中,是增加一个整数与保证导致-2147483648值2147483647?

In an unchecked context, is adding one to an integer with value 2147483647 guaranteed to result in -2147483648?

例如,用下面的代码

    const int first = int.MaxValue;
    int second = first;

    if ( second >= first )
    {
        Console.WriteLine( "First check" );
    }

    second++;

    if ( second >= first )
    {
        Console.WriteLine( "Second check" );
    }

在C ++中,这将是非常有效的两个首先检查和第二查询要打印,因为优化可以重用用于第二第一检查结果

In C++, it would be perfectly valid for both "First check" and "Second check" to be printed, as the optimizer can reuse the result of the first check for the second.

是C#的同一真?

推荐答案

从规格:

4.1.5整数类型

checked和unchecked运算符和语句用来控制溢出检查整型算术运算和转换(§7.6.12)。在checked上下文中,溢出产生编译时错误或导致出现System.OverflowException抛出。 在unchecked上下文中,溢出被忽略,并且不符合目标类型的任何高序位都被放弃。

The checked and unchecked operators and statements are used to control overflow checking for integral-type arithmetic operations and conversions (§7.6.12). In a checked context, an overflow produces a compile-time error or causes a System.OverflowException to be thrown. In an unchecked context, overflows are ignored and any high-order bits that do not fit in the destination type are discarded.

这是我能找到的行为的唯一描述,但似乎不够。所以,是的,加一 Int32.MaxValue 将导致价值 1 使用二进制补码表示。

That is the only description of the behavior that I could find, but it seems sufficient. So yes, adding one to Int32.MaxValue will result in the value -1 using two's complement representation.

这篇关于是C#/。.NET有符号整数溢出行为定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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