很多人第一次看到 getchar 的宣告都會愣一下:名字叫 get char,回傳型別卻是 int;putchar 是 put 一個 char,參數型別也是 int。名字和簽章對不上,看起來相當矛盾。
原因其實很樸素:電腦從來不區分誰是整數、誰是字元。
不需要參數,回傳 int,功能是從標準輸入的緩衝區 pop 出一個字元。由於字元在記憶體中存的是 ASCII 碼,也就是一個數字,所以 getchar 回傳的整數,正好就是該字元的 ASCII 碼。
關鍵在 EOF。C99 要求 getchar 在遇到檔案結尾時回傳 EOF,而 EOF 一般定義為 -1。這個值落在 char 的合理範圍內(尤其是 unsigned char 或某些平台上 char 為無符號時),若用 char 承接就無法與正常字元區分。於是標準乾脆把回傳型別定為 int,讓所有可能的字元值與 EOF 都能被無歧義地表達。
標準文件寫得很清楚:
7.19.7.6 The getchar function
Synopsis
1 #include <stdio.h>
int getchar(void);
Description
2 The getchar function is equivalent to getc with the argument stdin.
Returns
3 The getchar function returns the next character from the input stream
pointed to by stdin. If the stream is at end-of-file, the end-of-file
indicator for the stream is set and getchar returns EOF. If a read error
occurs, the error indicator for the stream is set and getchar returns EOF.
需要一個 int 參數,回傳 int。執行時,函式會把傳入的整數轉型為 unsigned char,寫入標準輸出的緩衝區,然後回傳這個字元(或 EOF)。用整數的理由與上面完全相同。
7.19.7.9 The putchar function
Synopsis
1 #include <stdio.h>
int putchar(int c);
Description
2 The putchar function is equivalent to putc with the second argument stdout.
Returns
3 The putchar function returns the character written. If a write error occurs,
the error indicator for the stream is set and putchar returns EOF.
如文件所述,一般實作中 getchar 與 putchar 都是巨集,最終展開為針對標準輸入與標準輸出的 fgetc 與 fputc。所有操作都只針對緩衝區中的一個字元,也就是一個位元組等大的資料。
實務上的結論很簡單:寫 int c;,用 while ((c = getchar()) != EOF) 當迴圈條件,永遠不要用 char 去接 getchar 的回傳值。這不是風格偏好,而是正確性問題。