字符数组下标警告

当我在这个例子中使用char数组下标时:
int main(){
    char pos=0;
    int array[100]={};

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

    return 0;
}

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

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

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

GCC手册说:

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

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

谢谢.

解决方法

这是因为int始终是签名的.

char不必.

char可以是签名或未签名,具体取决于实现. (有三种不同的类型 – char,signed char,unsigned 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
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...