字符数组下标警告 [英] Char array subscript warning

查看:50
本文介绍了字符数组下标警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

没关系,因为我启用了此警告.

Which is OK, because I have this warning enabled.

GCC 手册说:

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

-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 有效,而对其他有符号类型无效?

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?

谢谢.

推荐答案

这是因为 int 总是有符号的.

This is because int is always signed.

char 不是必须的.

char 可以是有符号或无符号的,具体取决于实现.(有三种不同的类型 - charsigned charunsigned char)

char can be signed or unsigned, depending on implementation. (there are three distinct types - 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
}

这篇关于字符数组下标警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆