Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it an infinite loop?

I tried to write the 255 ascii character to the console, but i've got an infinite loop

for(char i=0; i<256; i++) {
    cout << i << ' ';
}
like image 404
Hard Rain Avatar asked Nov 24 '12 15:11

Hard Rain


2 Answers

Because i can never be greater or equal to 256. It will overflow before it. Remember that it's type is char whose maximum value can be 255 if it is unsigned, otherwise 127 if it is signed.

Whether char is unsigned or signed, is implementation-defined. But usually, to my experience, it is signed, which means usually the maximum value char can attain is 127.

So i increments from 0 to 127, then becomes -128 from which it increases upto 127, and so on, well if it is signed. If it is unsigned, then it will go from 0 to 255, then next it will become 0 (due to overflow), and the story starts again, and again!

like image 62
Nawaz Avatar answered Sep 19 '22 17:09

Nawaz


Because all values of char are smaller than 256.

For the comparison, the char i is converted to int, resulting in a value between -128 and 127 usually (with signed two's complement 8-bit chars), or between 0 and 255 (inclusive) if char is an unsigned 8-bit type.

Once the maximal value a char can hold is reached, a further increment will lead to a wrap-around to 0 if char is unsigned, and to an implementation-defined conversion of the int value 128 that the increment produced to char when it is stored back, usually the result is -128, when char is signed.

like image 39
Daniel Fischer Avatar answered Sep 20 '22 17:09

Daniel Fischer