使用unsigned int而不是unsigned short更改行为

时间:2015-03-08 20:38:41

标签: c unsigned short integer-promotion

我正在尝试K& R的C编程语言中的htoi(char*)功能(练习2-3,第43页)。

该函数用于将十六进制字符串转换为基数10。

我相信我有它的工作。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

enum {hexbase = 16};
typedef enum{false, true} bool;

unsigned int htoi(char* s);
bool hasHexPrefix(char* s);

int main(int argc, char** argv) {   

    if(argc <= 1) {
        printf("Error: Not enough arguments.\n");
        return EXIT_FAILURE;
    }else {
        for(int i = 1; i < argc; i++) {
            unsigned int numericVal = htoi(argv[i]);
            printf("%s => %u\n",argv[i],numericVal);
        }
    }
}

unsigned int htoi(char* s) {
    unsigned int output = 0;
    unsigned int len = (unsigned int)(strlen(s));

    unsigned short int firstIndex = hasHexPrefix(s) ? 2 : 0;

    /* start from the end of the str (least significant digit) and move to front */
    for(int i = len-1; i >= firstIndex; i--) {
        int currentChar = s[i];
        unsigned int correspondingNumericVal = 0;
        if(currentChar >= '0' && currentChar <= '9') {
            correspondingNumericVal = currentChar - '0';
        }else if(currentChar >= 'a' && currentChar <= 'f') {
            correspondingNumericVal = (currentChar - 'a') + 10;
        }else if(currentChar >= 'A' && currentChar <= 'F') {
            correspondingNumericVal = (currentChar - 'A') + 10;
        }else {
            printf("Error. Invalid hex digit: %c.\n",currentChar);
        }
        /* 16^(digitNumber) */
        correspondingNumericVal *= pow(hexbase,(len-1)-i);
        output += correspondingNumericVal;
    }

    return output;
}

bool hasHexPrefix(char* s) {
    if(s[0] == '0')
        if(s[1] == 'x' || s[1] == 'X')
            return true;

    return false;
}

我的问题是来自htoi(char*)函数的以下行:

unsigned short int firstIndex = hasHexPrefix(s) ? 2 : 0;

当我删除short以使firstIndex成为unsigned int而不是unsigned short int时,我会获得无限循环。

因此,当我从shtoi(char* s)的后面开始时,i >= firstIndex永远不会评估为假。

为什么会这样?我是否遗漏了一些微不足道的事情,或者我做了一些非常错误的事情导致这种未定义的行为?

1 个答案:

答案 0 :(得分:4)

firstIndexunsigned int时,在i >= firstIndex中,i会因为通常的算术转换而转换为unsigned int。因此,如果i为负,则它将成为比较表达式中的一个大整数。当firstIndex unsigned short int i >= firstIndex firstIndex时,int被提升为for(int i = len-1; i >= firstIndex; i--) ,并且会比较两个有符号整数。

您可以更改:

for(int i = len-1; i >= (int) firstIndex; i--)

{{1}}

在两种情况下都有相同的行为。

相关问题