2014-10-01 52 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