字符数组下标警告

Mih*_*lko 6 c arrays gcc warnings subscript

当我在这个例子中使用char数组下标时:

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

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到警告,我正在使用char数组下标:

警告:数组下标的类型为'char'[-Wchar-subscripts]

哪个好,因为我启用了此警告.

GCC手册说:

-Wchar-subscripts如果数组下标的类型为"char",则发出警告.这是导致错误的常见原因,因为程序员经常忘记这种类型是在某些机器上签名的.-Wall启用此警告.

因此,此警告应防止使用负数组索引.我的问题是,为什么此警告仅在char上有效,而在其他已签名类型上无效?

谢谢.

mil*_*bug 8

这是因为int总是签名.

char 不必.

char可以是签名或未签名,具体取决于实现.(有三种不同类型的- ,char,)signed charunsigned char

但是问题是什么?我可以使用0到127之间的值.这会伤害我吗?

哦,是的,它可以.

//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
}
Run Code Online (Sandbox Code Playgroud)