#include <iostream>
using namespace std;
int main()
{
unsigned char counter = 0;
for (counter = 0; counter <= 255; counter++) {
printf("%d ", counter);
}
return 0;
}
Correct Output is Infinite loop But I thought output is 0,1,...255 because unsigned char ranges from 0 to 255.when the counter becomes 256 then only it exceeds the range. but here our condition is counter <=255 Please clear my doubt
Think about unsigned char as a Byte: 0 -> 0b00000000 1 -> 0b00000001... 255 -> 0b11111111
Then the next number is 0 because you can't have a 9th bit. So after 0b11111111 it's 0b00000000.
That's why it is an infinite loop, it will never reach 256 and will always stay between 0 and 255.
This will result in infinite loop because condition (counter <= 255)
in if
loop is always true
.
There is no way for this condition to be false
: variable counter
can not contain values higher than 255.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.