1
votes
#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

2
Can you show us the result in the console plese? - Adrien G.
nope... counter is an unsigned char so is never ever holding the 256 value... - ΦXocę 웃 Пepeúpa ツ
Changed tag to [c++] because that's what you're writing - Geoffroy
For an unsigned char type with a current value of 255, the ++ operator will make its new value 0. - Adrian Mole
unsigned char is between 0 and 255. You check in the loop <= 255 and it will always be true. When counter is at 255 and you try to add 1 to it, it overflows and the value resets to 0. - user9872569

2 Answers

5
votes

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.

2
votes

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.