[問題] 關於C99 6.3.1.8 Usual arithmetic conve

作者: csosmo (Be Back!)   2014-05-06 17:10:51
開發平台(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):
作者: azureblaze (AzureBlaze)   2014-05-06 17:34:00
step A.錯了 int可以完整表示short和ushort所以兩邊都promote成int
作者: csosmo (Be Back!)   2014-05-06 17:43:00
請問哪種case會promote成unsigned int?如果case2, 兩個operand都promote成int,結果為何不是相等?
作者: Fenikso (薪水小偷)   2014-05-06 18:21:00
case2.因為是-12(short)和65534(ushort)分別promote成int再拿來比較哪種case會promote成unsigned int? -> case 3
作者: csosmo (Be Back!)   2014-05-06 20:26:00
瞭解, 感謝專家們解答!

Links booklink

Contact Us: admin [ a t ] ucptt.com