Kanru’s 探險日誌

當發現美好的事物時,所要做的第一件事,就是把它分享給所有人

Short, Int, 加加減減

with one comment

short x = 32767;
x = x + 2;

在 C 裡面,我們可能不小心寫出這樣的 code 而不自覺會造成 overflow,但是在 C# 則會得到

error CS0266: Cannot implicitly convert type ‘int’ to ’short’. An explicit conversion exists (are you missing a cast?)

要改成

x = (short)(x +2);

才行; 不過神奇的是,如果寫成

x += 2;

則不會有任何問題的直接 overflow… 這究竟是什麼樣的設計考量呢?

Written by Kanru Chen

February 16th, 2006 at 12:26 pm

Posted in Programming

Tagged with

One Response to 'Short, Int, 加加減減'

Subscribe to comments with RSS or TrackBack to 'Short, Int, 加加減減'.

  1. 那應該是 implicitly casting

    neo anderson

    4 Apr 06 at 9:37 pm

Leave a Reply