看板 C_and_CPP 關於我們 聯絡資訊
Hi all 大家好,這裡有個問題想請教 開發平台(Platform): (Ex: Win10, Linux, ...) windows 10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) Visual studio 2019,.c file 問題(Question): unsigned int a=10; int b=-2; unsigned int c=1; if(a*b>c) { printf("Hello\n"); } else { prntf("No Hello\n"); } 預期的正確結果(Expected Output): No Hello 錯誤結果(Wrong Output): Hello 補充說明(Supplement): ref:https://en.cppreference.com/w/c/language/conversion 我的理解: a和b的rank應該是相同的。 且根据integer promotion的規則,a*b應該是先各自promote成int再乘,怎麼會是promot e成unsigned? 開個大決:感覺這裡沒人會阿XD,ptt沒人才惹。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.217.10.84 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1651353852.A.140.html
oToToT: 至少c是unsigned就會在比較時把a*b的結果轉unsigned了吧05/01 05:49
karmel: 同樓上 可以把a*b的結果print出來看看05/01 05:54
firejox: 阿不是補充說明都說完規則了,為什麼會覺得是轉成signed05/01 08:59
firejox: type (′・ω・`)05/01 08:59
firejox: If the unsigned type has conversion rank greater tha05/01 09:01
firejox: n or equal to the rank of the signed type, then the05/01 09:01
firejox: operand with the signed type is implicitly converted05/01 09:01
firejox: to the unsigned type05/01 09:01
喔喔,原來還有這一段,感謝。
firejox: 會轉成 signed type 也就只有這段 If the signed type c05/01 09:06
firejox: an represent all values of the unsigned type, then t05/01 09:06
firejox: he operand with the unsigned type is implicitly conv05/01 09:06
firejox: erted to the signed type05/01 09:06
而且我想我也是誤解了integer promotion的意思,不過整體而言還是謝謝大大幫忙。If int can "represent" the "entire range of values of the original type "(or the range of values of the original bit field), the value is converted to type int . ※ 編輯: ManOfSteel (49.217.10.84 臺灣), 05/01/2022 17:24:22
wulouise: 你開-Wall找warning看就知道了 05/07 14:54
OnlyRD: 問題太低級,連回答都懶。 05/15 20:18