Char array subscript warning

与世无争的帅哥 提交于 2019-11-26 22:03:33

问题


when I use char array subscript as in this example:

int main(){
    char pos=0;
    int array[100]={};

    for(pos=0;pos<100;pos++)
        printf("%i\n", array[pos]);

    return 0;
}

I am getting warning that I am using char array subscript:

warning: array subscript has type ‘char’ [-Wchar-subscripts]

Which is OK, because I have this warning enabled.

GCC manual says:

-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.

So this warning should prevent of using negative array index. My question is, why is this warning active only on char and not also on other signed types?

Thank you.


回答1:


This is because int is always signed.

char doesn't have to.

char can be signed or unsigned, depending on implementation. (there are three distinct types - char, signed char, unsigned char)

But what's the problem? I can just use values from 0 to 127. Can this hurt me silently?

Oh, yes it can.

//depending on signedess of char, this will
//either be correct loop,
//or loop infinitely and write all over the memory
char an_array[50+1];
for(char i = 50; i >= 0; i--)
{
    an_array[i] = i;
    // if char is unsigned, the i variable can be never < 0
    // and this will loop infinitely
}



回答2:


Plainly put, it's complaining about your index being of type character.

Simply convert pos to an int and the warning will disappear.

As for why this warning appears, you've stated it yourself. A char datatype can only address values from 0 - 255 (if unsigned) or even just 127 (if signed). For a normal array, that's a rather meager number and you could quickly forget about the signed bit and accidentally access array location -128 (by actually accessing array element 128).

As long as your array is smaller than 127, you'll be fine and you can ignore the warning, but let's be honest...these three extra bytes in your memory footprint won't make your application inefficient, will it?




回答3:


Because native char can be either unsigned or signed.

Note that it's perfect legal to use negative subscript. For instance:

int arr[10];
int *ptr = arr[5];

Now I can use ptr[-1] which is equivalent to arr[4]. If char happens to be unsigned in the implementation, it can never be a negative value.



来源:https://stackoverflow.com/questions/15006660/char-array-subscript-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!