'C++ for loop doesnt exit [closed]
I have a for loop that initializes an array with dynamic data
the code looks like this
for (char i=0; i<256; i++){
data[i] = i; // some random dynamic data
}
I figured out that its always smaller than 256 cause the max positive number it can store is 127. So i made this an unsinged char. But it still runs forever.
I fixed this by lowering to 254
for (unsigned char i=0; i<254; i++){
// do the things
}
and it worked.
My question is: why wont it work with 255?
edit: fixed small "typo" on the first loop plz note that those 2 loops dont run together im just showing you the different iterations of the code
Solution 1:[1]
The following loop will do what you'd expect: run 255 times
for (unsigned char i = 0; i < 255; i++) {
//stuff...
}
If, however, you want it to run 256 times like you expected in the first case, then the type of i is the problem. You can't use an unsigned char to run a loop 256 times because you exhaust all possible values. An 8bit unsigned integer can only go from 0 to 255, so conditions like i < 256 or i <= 255 will always be true. Consider using int or size_t (since you're working with arrays).
for (size_t i = 0; i < 256; i++) {
//stuff...
}
If you insist on using unsigned char, the only option would be a do-while where the comparison occurs at the end of each loop. The following will run 256 times.
unsigned char i = 0;
do {
//stuff...
} while (i++ != 255); // First check that i isn't 255 and then increment i
Solution 2:[2]
It actually works but after reaching i=255 and doing the stuff, it resets to 0 as 255+=1=256 which goes to 0 as the range of unsigned char is [0, 255].
So instead of
for (unsigned char i=0;i<256;i++){
// do stuff
}
you should try
for (unsigned char i=0;;i++){
//do stuff
if(i==255)break;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | guard3 |
| Solution 2 | Tushar Jain |
