Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the unsigned keyword do here?

Tags:

c++

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?

like image 850
lowriderzxxx Avatar asked Jul 05 '13 00:07

lowriderzxxx


Video Answer


1 Answers

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.

like image 102
i Code 4 Food Avatar answered Oct 11 '22 14:10

i Code 4 Food