字符数组下标警告

前端之家收集整理的这篇文章主要介绍了字符数组下标警告前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我在这个例子中使用char数组下标时:
  1. int main(){
  2. char pos=0;
  3. int array[100]={};
  4.  
  5. for(pos=0;pos<100;pos++)
  6. printf("%i\n",array[pos]);
  7.  
  8. return 0;
  9. }

我收到警告,我正在使用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之间的值.这可以悄悄地伤害我吗?

哦,是的,它可以.

  1. //depending on signedess of char,this will
  2. //either be correct loop,//or loop infinitely and write all over the memory
  3. char an_array[50+1];
  4. for(char i = 50; i >= 0; i--)
  5. {
  6. an_array[i] = i;
  7. // if char is unsigned,the i variable can be never < 0
  8. // and this will loop infinitely
  9. }

猜你在找的C&C++相关文章