讀完了第二章:類型,運算子和運算式。下面列舉一些有啟發的點:
- 關於類型(Type),作者用一句話很精闢地作了概括:"The type of an object determines the set of values it can have and what operations can be performed on it."一個對象的類型決定了它能夠取值的集合以及能對它進行的操作。
- 關於變數名,許多類C進階語言的編程規範都推薦類欄位的名字以底線"_"開始,但在C語言中,所有的變數名都不推薦用"_"開始。作者說"Don't begin variable names with underscore, however, since library routines often use such names."因為庫程式會使用這樣的名字。
- 整形類型分為short, int和long,它們的長度怎麼區分?作者指出,"The intent is that short and long should provide different lengths of integers where practical; int will normally be the natural size for a particular machine."所以在現在的32位機器上,int型的長度就是32。"where practical"意思是short和long的長度是由編譯器決定的,只要short不比int長,int不比long長就可以。在16位的機器上,short和int都是16位長。和整形類似,float, double和long double的長度也是依賴於具體的機器的。它們可以代表一種、兩種或者三種不同的長度。
- 常數的首碼和尾碼。首碼有0(八進位)和0x(十六進位),尾碼有U(unsigned)、L(long)和F(float)。首碼和尾碼可以同時加,比如OxFUL。
- 關於為什麼不用整形常量直接代替字元型常量,如48代替'0',作者解釋說,"If we write '0' instead of a numeric value like 48 that depends on the character set, the program is independent of the particular value and easier to read."由此可見,字元型常量雖然內部存的是一個整形值,但這個值取決於機器的字元集。設立字元型常量可以使字元獨立於具體的字元集,並增加程式可讀性。
- 用八進位和十六機製表示字元,分別採用下面的形式:'/ooo'和'/xhh'。它們都是一個字元,值為一個整數。
- 關於'/0',作者提到,"The character constant '/0' represents the character with value zero, the null character. '/0' is often written instead of 0 to emphasize the character nature of some expression, but the numeric value is just 0"。'/0'的值就是0,寫成這樣只是為了強調它的字元屬性。
- 浮點數還可以這樣被賦值:float eps = 1.0e-5;,以前沒有注意過。
- 非局部變數只能被初始化一次,並且只能被初始化一個常量運算式。外部變數和靜態變數預設被初始化成0,而未被初始化的局部變數則有不確定的值。
- const可以被用在數組參數上,以防止數組被調用的函數改變。如:int strlen(const char[]);
- 這個getbits函數寫得很漂亮,從中可以得到不少關於位操作的啟發:
/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 << n);
}
用求反運算子~使得程式獨立於具體機器的字長,因而具有可移植性。