How to get out of an infinite loop?
unsigned char half_limit = 130;
for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
//smth is happening;
}
Help, please.
Thank you!
How to get out of an infinite loop?
unsigned char half_limit = 130;
for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
//smth is happening;
}
Help, please.
Thank you!
Make your loop variable an int
.
unsigned char
can't exceed 255, so incrementing i
past that will wrap it to 0.
2*130
is 260, because the type of literal 2
is int
, and multiplying an int
by unsigned char
you get an int
.
Thus, when i
is an unsigned char
, your loop termination condition will never be satisfied since i
will always be less than 260, hence the infinite looping.
How to get out of an infinite loop?
Paradoxically, you cannot. Because if you get out of a loop, then the loop was finite.
I suggest you take a look at this post:
Or you could try this approach:
#include <stdio.h>
#include <stdlib.h>
int main(){
int half_limit = 130;
int i;
for (i = 0; i < 2 * half_limit; ++i){
printf("%d\n", i);
}
return 0;
}
As i
is of type unsigned char
which is of size 1byte and can hold 0 to 255 values.
If you increment i
after 255 (i.e 0xFF) expectation is i
to become 256 but i
hold value 0 due overflow. (i.e in 256 is equivalent to 0x100 and only lower byte value will be available in i
)
In order to run loop from 0 to 260 you need to change the type of i
which can hold value beyond 255.
short int
or int
is preferable,
unsigned char half_limit = 130;
for (int i = 0; i < 2 * half_limit; ++i)
{
//smth is happening;
}
You're having an infinite loop because of unsigned char
range which is from 0 to 255. So basically, i
never reaches 2 * half_limit
. i
starts from 0 then goes to 255
then goes to 0
again and so on and so forth.