標籤:
先上兩個解釋我的疑惑的連結:
http://en.cppreference.com/w/cpp/language/operator_arithmetic
https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx
開始我是看 <<Expert C programming -- Deep C Secrets>>這本書(中文譯作 C專家編程), chapter 1 裡面的how quite is a quite change 這一小節, 有這樣一段代碼:
#include <stdio.h>
int main()
{
if(-1 < (unsigned char)1)
printf("-1 is less than (unsigned char)1: ANSI semantics.\n");
else
printf("-1 is NOT less than (unsigned char)1: K&R semantics.\n");
return 0;
}
我用了vs2013和gcc 4.9.1分別去編譯運行, 都是ANSI的語義.列印第一條語句.
然後改成這樣
#include <stdio.h>
int main()
{
if(-1 < (unsigned int)1)//或者是unsigned
printf("1111111111.\n");
else
printf("222222222222222.\n");
return 0;
}
gcc 4.9.1編譯運行(未加任何特殊編譯選項)的結果是列印第二條. 而vs2013預設編譯不通過, error:負數轉變成了無符號數.
開始看 <<Expert C programming -- Deep C Secrets>>這本書這裡時有點偷懶, 只記得了這兩句話:
Operands with different types get converted when you do arithmetic. Everything is converted to the type of the floatest, longest operand, signed if possible without losing bits.
實際上完整的規則還是本文開頭的哪兩個連結靠譜.
我覺得 best practice應當是盡量少用強制轉換, 誰想去記憶那些無聊的規則.
關於 C 的 arithmetic conversion (進行 算術運算 時的 強制轉換規則)