daygle
daygle

Reputation: 61

C++ Warning Array Subscript Has Type 'char'

I require some help with code that throws a 'Warning array subscript has type 'char' [-Wchar-subscripts]' message.

The code in question is:-

static
const long hextable[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-19
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 30-39
    -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
    2, 3, 4, 5, 6, 7, 8, 9, -1, -1, // 50-59
    -1, -1, -1, -1, -1, 10, 11, 12, 13, 14,
    15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 70-79
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, // 90-99
    13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 110-109
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 130-139
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 150-159
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 170-179
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 190-199
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 210-219
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 230-239
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1
};

long hex2long(const char* hexString)
{
    long ret = 0;
    while (*hexString && ret >= 0)
    {
        ret = (ret << 4) | hextable[*hexString++];
    }
    return ret;
}

Now it appears that the line ret = (ret << 4) | hextable[*hexString++]; has issues.

I am hoping someone can assist me re-structuring this code to prevent the error.

Upvotes: 1

Views: 276

Answers (1)

Omarito
Omarito

Reputation: 577

Change const char* to const unsigned char*.

From GCC Warnings:

-Wchar-subscripts Warn if an array subscript has type char. This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by -Wall.

The compiler doesn't want you to use negative indices for the array, so it throws a warning to let you know of this potential problem.

Upvotes: 4

Related Questions