[問題] C unsigned long的問題
開發平台(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
07/18 00:04, 2F
→
07/18 00:06, , 3F
07/18 00:06, 3F
推
07/18 01:54, , 4F
07/18 01:54, 4F
→
07/18 01:54, , 5F
07/18 01:54, 5F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):