簡體   English   中英

8位和16位整數的算術運算

[英]Arithmetic operations with 8 and 16 bit integers

我確實理解為什么這會產生編譯時錯誤:

short x = 1;
short y = 2;
short z = x + y; // compile-time error

我已經理解了為什么運行時沒有任何問題:

short x = 1;
short y = 2;
x += y; // all right, because of c# specs section 7.17.2

但是我不知道為什么這也行得通:

short x = (short)1 + (short)2;

我期望得到與第一個示例相同的編譯時錯誤,但是它運行成功...為什么?

由於您使用的是常量值,因此編譯器可以檢測到它是允許的, 在編譯時對其進行評估,然后讓其執行。 生成的IL與輸入short x = 3;的結果相同short x = 3;

請注意,以下內容也可以工作(出於相同的原因):

const short x = 1;
const short y = 2;
short z = x + y; 

但這失敗了:

const short x = 32000;
const short y = 32001;
short z = x + y;

請注意,C#語言規范6.1.9隱式常量表達式轉換對此進行了介紹:

  • 可以將類型為int的常數表達式(第7.19節)轉換為sbyte,byte,short,ushort,uint或ulong類型,前提是該常數表達式的值在目標類型的范圍內。

您的最后一個片段只是編譯為常數3 編譯器不需要在int調用任何運算符,它只是在編譯時計算並存儲值。

它與short x = 3;相同short x = 3;

這是生成的IL

IL_0001:  ldc.i4.3    //Load the constant 3 into evaluation stack
IL_0002:  stloc.0     // stores the value in stack to x

我不知道為什么這也行得通:

 short x = (short)1 + (short)2; 

編譯器在編譯時評估rhs表達式,並可以證明結果在范圍之內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM