在C中使用char迭代器的FOR循环是否可行? [英] Are FOR loops with char iterators in C possible?

查看:126
本文介绍了在C中使用char迭代器的FOR循环是否可行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用无符号字符作为迭代器时遇到问题.使用以下代码将导致卡在FOR循环中. 输出看起来像这样.

I'm having a problem using an unsigned char as an iterator. Using the following code results in being stuck inside a FOR loop. The output looks like this.

unsigned char i;
char * arr;
int * freq;
arr = (char *)(malloc(256*sizeof(char)));
freq = (int *)(malloc(256*sizeof(int)));
for (i=0; i<=255;i++){
    arr[i]=i;
    freq[i]=0;
    printf("%c",i);
}

我的问题是为什么会这样?是由于使用无符号字符作为迭代器吗?

My question is why this happens? Is it due to using an unsigned char as an iterator?

推荐答案

i <= 255

如果i的类型为unsigned char,并且在您的平台上该类型为8位(可能是8位),则表达式将始终为true,并且您将遇到无限循环.但是,这是定义明确的行为. unsigned char会简单地回绕,一旦达到255,其值就会再次从0开始.

If i is of type unsigned char and that type is 8 bit on your platform (which it likely is), then the expression will always be true and you have an infinite loop. It is well-defined behavior, though. The unsigned char will simply wrap around and its value will start at 0 again once it has reached 255.

解决方案当然很简单:将i的类型更改为int.

The solution is simple of course: change the type of i to int.

为避免将来出现此类意外情况,请确保打开编译器的警告.如果我使用GCC编译假循环并将其传递给-Wall-Wextra标志,它将告诉我.

To avoid such surprises in the future, make sure to turn on your compiler's warnings. If I compile the bogus loop with GCC and pass it the -Wall and -Wextra flags, it will tell me this.

main.c: In function ‘main’:
main.c:5:17: warning: comparison is always true due to limited range of data type [-Wtype-limits]
   for (i = 0; i <= 255; ++i)
                 ^

这篇关于在C中使用char迭代器的FOR循环是否可行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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