[英]for loop condition always true
I have a For loop in C: 我在C中有一个For循环:
u8 i;
for (i=0; i <= 255; i++)
{
//code
}
Now the compiler complains that "comparison is always true due to limited range of data type" I understand that 255 is u8 max but a for loop must have a condition. 现在编译器抱怨“由于数据类型的范围有限,比较总是正确的”我知道255是u8 max但是for循环必须有条件。 What should I put there then?
那我应该放在那里? Thanks.
谢谢。
uint8_t i=0;
do {
//code
}while(++i);
what is u8
? 什么是
u8
? if it means 8-bit unsigned int, then 255+1 gives zero again, so the loop starts over again. 如果它意味着8位无符号整数,则255 + 1再次给出零,因此循环重新开始。 you should use larger integer type.
你应该使用更大的整数类型。 or use
do-while
as suggested in replies 或使用回复中建议的
do-while
u8 i=0,iold;
do{
//code
iold=i++;
}while(iold<i);
u8 someFunction()
{
int i;
for (i = 0; i < 256; i++)
{
// do something with i here and /or break
}
if (i == 256)
{
// loop ran completely without a break
}
return i; // will convert i to "u8" type (256 will become 0)
}
A for
loop doesn't necessarily need a condition. for
循环不一定需要条件。 If you want the loop to not have any condition at all, you can write: 如果您希望循环根本没有任何条件,您可以写:
for (i = 0; 1 ; i++)
or 要么
for (i = 0; ; i++)
But beware that i
will overflow after reaching 255, and start over back from zero each time. 但要注意
i
会在达到255后溢出,并且每次从零开始重新开始。
If you don't want it to loop infinitely, then either place a break;
如果你不想让它无限循环,那么要么
break;
somewhere inside the loop, or use an appropriate condition inside the condition field of the for
loop. 在循环内的某个地方,或在
for
循环的条件字段内使用适当的条件。
And to be honest, I am not sure why your compiler is even complaining about a condition being always true... 说实话,我不确定为什么你的编译器甚至抱怨条件总是如此......
What should I put there then?
那我应该放在那里?
Use a larger type like int
type. 使用更大的类型,如
int
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.