关于C#:为什么在byte.maxvalue中添加1会导致256而不是溢出

why adding 1 to byte.MaxValue results in 256 not an overflow

本问题已经有最佳答案,请猛点这里访问。

我在C中有一段简单的代码,用于在类型的maxValue中添加1时显示溢出错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte a = byte.MaxValue;
            byte b = 1;
            Console.WriteLine("Max+1 is : {0}", a+b);

            Console.ReadLine();
        }
    }
}

但它不会产生溢出和错误的结果,而是生成正确的值:256为什么?而C中字节变量的最大值为255。我错了吗?


int中,对任何小于int的内容进行添加。这在数字促销下的标准ECMA-334 C规范中进行了描述。

12.4.7数字促销

When overload resolution rules (§12.6.4) are applied to this set of
operators, the effect is to select the first of the operators for
which implicit conversions exist from the operand types. [Example: For
the operation b * s, where b is a byte and s is a short, overload
resolution selects operator *(int, int) as the best operator. Thus,
the effect is that b and s are converted to int, and the type of the
result is int. Likewise, for the operation i * d, where i is an int
and d is a double, overload resolution selects operator *(double,
double) as the best operator. end example]

此外,如果要捕获溢出,则需要使用checked关键字

例子

1
2
3
byte a = byte.MaxValue;
byte b = 1;
byte c = checked((byte)(a + b));

其他资源

已检查(C参考)

By default, an expression that contains only constant values causes a
compiler error if the expression produces a value that is outside the
range of the destination type. If the expression contains one or more
non-constant values, the compiler does not detect the overflow.
Evaluating the expression assigned to i2 in the following example does
not cause a compiler error.