[問題] C unsigned long的問題

看板C_and_CPP作者 (牛頓運動定律)時間8年前 (2017/07/17 14:35), 編輯推噓2(203)
留言5則, 3人參與, 最新討論串1/2 (看更多)
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): #include <stdio.h> void print_x(unsigned long x) { printf("=> 0x%lx\n",x); } int main() { print_x(0x80000000); print_x((1<<31)); } 想問為何同樣是數字一個不會overflow 一個會?? 餵入的資料(Input): 0x80000000 1<<31 最近看到別人寫的code都會用1UL << 31應該也是怕overflow ?? 預期的正確結果(Expected Output): => 0x80000000 => 0x80000000 錯誤結果(Wrong Output): => 0x80000000 => 0xffffffff80000000 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.164.70.71 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1500302114.A.2FA.html

07/17 23:11, , 1F
第二個拆成兩行做
07/17 23:11, 1F

07/18 00:04, , 2F
因為你單寫 1 的型態是 int, 寫 1UL 才是 unsigned long
07/18 00:04, 2F

07/18 00:06, , 3F
0x80000000 則比較有趣, int 裝不下, 它變成 unsigned int
07/18 00:06, 3F

07/18 01:54, , 4F
overflow是當一組byte要解析成sigined或unsigned才會發
07/18 01:54, 4F

07/18 01:54, , 5F
07/18 01:54, 5F
文章代碼(AID): #1PRCiYBw (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1PRCiYBw (C_and_CPP)