[問題] 關於C99 6.3.1.8 Usual arithmetic conve

看板C_and_CPP (C/C++)作者 (Be Back!)時間12年前 (2014/05/06 17:10), 12年前編輯推噓2(206)
留言8則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 2008 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) none 問題(Question): 各位專家 關於C99 6.3.1.8 Usual arithmetic conversions http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf 我寫了一段測試程式 我預期case2, case3的output應該要相同 (我預期都應該為1, 0, 0) 但是實際上VC++ 2008 跑出來的case2, case3結果不同 case1, 2, 3我的理解如下 再麻煩專家們指點下盲點在哪 感謝 =================================================================== case1. both two operands are converted to unsigned int (i. e. 0xffffff4) before comparison. So, they are equal. case2, case3: I think the results of case2, case3 should be the same as following. step A. integer promotion short type (0xfff4) -> int (0xfffffff4) unsigned short -> unsigned int (0x0000fff4). step B. arithmetic conversions => use "unsigned" type because the rank of int and unsinged int are the same. So, the unsigned 0xfffffff4 is larger than unsigned 0x0000fff4. But, case2 result is not what I expect. 餵入的資料(Input): none 預期的正確結果(Expected Output): [1] 0, 0, 1 [2] 1, 0, 0 [3] 1, 0, 0 錯誤結果(Wrong Output): [1] 0, 0, 1 [2] 0, 1, 0 [3] 1, 0, 0 程式碼(Code):(請善用置底文網頁, 記得排版) int i_num = -12; unsigned int ui_num = -12; short s_num = -12; unsigned short us_num = -12; int i_num2 = s_num; unsigned int ui_num2 = us_num; printf("[1] %d, %d, %d\n", i_num > ui_num, i_num < ui_num, i_num == ui_num); printf("[2] %d, %d, %d\n", s_num > us_num, s_num < us_num, s_num == us_num); printf("[3] %d, %d, %d\n", i_num2 > ui_num2, i_num2 < ui_num2, i_num2 == ui_num2); 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.250.82.111 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1399367454.A.291.html ※ 編輯: csosmo (111.250.82.111), 05/06/2014 17:22:51

05/06 17:34, , 1F
step A.錯了 int可以完整表示short和ushort
05/06 17:34, 1F

05/06 17:34, , 2F
所以兩邊都promote成int
05/06 17:34, 2F

05/06 17:43, , 3F
請問哪種case會promote成unsigned int?
05/06 17:43, 3F

05/06 17:44, , 4F
如果case2, 兩個operand都promote成int,結果為何不是相等?
05/06 17:44, 4F

05/06 18:21, , 5F
case2.因為是-12(short)和65534(ushort)分別promote成int
05/06 18:21, 5F

05/06 18:22, , 6F
再拿來比較
05/06 18:22, 6F

05/06 18:26, , 7F
哪種case會promote成unsigned int? -> case 3
05/06 18:26, 7F

05/06 20:26, , 8F
瞭解, 感謝專家們解答!
05/06 20:26, 8F
文章代碼(AID): #1JQASUAH (C_and_CPP)
文章代碼(AID): #1JQASUAH (C_and_CPP)