[C#] 數值溢位

  • 399
  • 0

以下範例Add有隱含的錯誤,若num1 + num2超過 int.MaxValue則會報錯。
The operation overflows at compile time in checked mode

static void Main(string[] args)
{
	int num1 = int.MaxValue, num2 = 20;
	int result = Add(num1, num2);

	Console.WriteLine(result);
}

static int Add(int num1, int num2)
{
	return num1 + num2;
}

正確作法有兩種。

1. 如遇到溢位則報出Exception(checked)

static void Main(string[] args)
{
	int num1 = int.MaxValue, num2 = 20;
    try{
        int result = Add(num1, num2);
        
        Console.WriteLine(result);
    }catch(Exception ex){
        Console.WriteLine(ex.Message);
    }
	
}

static int Add(int num1, int num2)
{    
    checked{
	    return num1 + num2;
    }
}

2. 如遇到溢位不報錯依然執行(unchecked)

static void Main(string[] args)
{
	int num1 = int.MaxValue, num2 = 20;
    try{
        int result = Add(num1, num2);

        Console.WriteLine (result);
    }
    catch (Exception ex)
    {
        Console.WriteLine (ex.Message);
    }

}

static int Add (int num1, int num2)
{
    unchecked
    {
        return num1 + num2;
    }
}

參考資料:

https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/keywords/checked-and-unchecked