2014-10-01 32 views
0

我有一個關於getopt函數的問題,如下面的代碼所示,「ch」的類型是「int」,但在switch子句中,它被視爲「char」 ..我很困惑,爲什麼?鋤頭getopt()處理char類型

Thansk !!

int main(int argc, char **argv) 
{ 
extern int optind; 
extern char * optarg; 
int ch; 
char * format = "f:hnBm:"; 

// Default makefile name will be Makefile 
char szMakefile[64] = "Makefile"; 
char szTarget[64]; 
char szLog[64]; 

while((ch = getopt(argc, argv, format)) != -1) 
{ 
    switch(ch) 
    { 
     case 'f': 
      strcpy(szMakefile, strdup(optarg)); 
      break; 
     case 'n': 
      break; 
     case 'B': 
      break; 
     case 'm': 

      strcpy(szLog, strdup(optarg)); 
      break; 
     case 'h': 
     default: 
      show_error_message(argv[0]); 
      exit(1); 
    } 
} 

回答

1

在C中,char實際上只是一定尺寸的整和int可以隱式轉換成一個,因此它可以透明地。

+0

但是,當我printf(「%d」,ch)時,無論我輸入什麼值,它都會給出值1 'f','B'or'm'...似乎沒有區別。你知道爲什麼 – Lily 2014-10-01 02:56:19

+0

我在你的問題中運行了確切的代碼,只是在循環的開頭添加了'printf',並看到了不同的數字。當你粘貼它時,你在代碼中改變了什麼......? – 2014-10-01 03:00:27

+0

嗨馬蒂,我再次運行。這樣可行!!抱歉! – Lily 2014-10-01 03:13:22

0

當您比較C中的char和int(例如在switch語句中)時,編譯器會自動將char轉換爲int類型。因此,在上面的switch語句中,'f'會自動轉換爲102,這是對應於ASCII'f'的數值。因此,在你的代碼中的switch語句中,'ch'不是真的被認爲是char。相反,case語句中的字符都被轉換爲int,因此它們與「ch」類型匹配。

+0

但是當我printf(「%d」,ch)時,無論我輸入'f','B'or'm',它都會給出1的值......好像有沒有任何不同 – Lily 2014-10-01 02:54:10