Char array subscript warning

后端 未结 3 1315
粉色の甜心
粉色の甜心 2020-12-07 01:51

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


        
3条回答
  •  旧时难觅i
    2020-12-07 02:37

    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
    }
    

提交回复
热议问题