hoe getopt()处理char类型

时间:2014-10-01 02:38:38

标签: getopt

我有一个关于getopt函数的问题,如下面的代码所示,“ch”的类型是“int”,但在switch子句中,它被视为“char”..我很困惑为什么?< / p>

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);
    }
}

2 个答案:

答案 0 :(得分:1)

在C中,char实际上只是一个特定大小的整数,int可以隐式转换为一个,因此它可以透明地工作。

答案 1 :(得分:0)

比较C中的char和int(例如在switch语句中)时,编译器会自动将char转换为int类型。所以在上面的switch语句中,&#39; f&#39;自动转换为102,这是对应于ASCII&#39; f&#39;的数值。因此,在代码中的switch语句中,&#39; ch&#39;并不是真的被视为焦炭。相反,case语句中的字符都被转换为int,因此它们匹配&#34; ch&#34;

的类型