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 << ' ';
}
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!
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 char
s), 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With