微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

字符数组下标警告

当我在这个例子中使用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
}

原文地址:https://www.jb51.cc/c/111387.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐