I wrote some C++ code to show ASCII characters on a console which I found in a book i was reading. The code looked like this:
#include <iostream>
using namespace std;
int main()
{
for (unsigned char i = 32; i<128; i++)
cout << i;
int response;
cin >> response;
return 0;
}
When I take away the unsigned
keyword and use signed
instead, the results become infinite and the PC beeps until I shut off the executable file. But when I use an int i
variable instead I don't need to unsign the variable. Why is that?
unsigned
simply means that the number won't become negative. Yeah, number, because a char
really is just an 8-bit integer.
So when unsigned
, every bit is used in the non-negative range, which will go from 0 to 255. When you leave out and use a signed
(default) char, the range will go from -128 to 127, thus it will always be less than 128 and go into an infinite loop.
The beep you hear is due to the char of value 7 being "printed".
An int
, on the other hand, even when signed goes all the way from -2.147... billions to +2.147 billions, so it will iterate normally until reaching 128 and stopping.
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