Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning negative value to char

Tags:

c++

c

Why does the following code print "?" ? Also how can -1 be assigned to an unsigned char?

char test;
unsigned char testu; //isn't it supposed to hold values in range 0 - 255?
test = -1;
testu = -1;
cout<<"TEST CHAR = "<<test<<endl;
cout<<"TESTU CHAR = "<<testu<<endl;
like image 944
Nemo Avatar asked Dec 07 '25 06:12

Nemo


2 Answers

unsigned simply affects how the internal representation of the number (chars are numbers, remember) is interpreted. So -1 is 1111 1111 in two's complement notation, which when put into an unsigned char changes the meaning (for the same bit representation) to 255.

The question mark is probably the result of your font/codepage not mapping the (extended) ASCII value 255 to a character it can display.

I don't think << discerns between an unsigned char and a signed char, since it interprets their values as ASCII codes, not plain numbers.

Also, it depends on your compiler whether chars are signed or unsigned by default; actually, the spec states there's three different char types (plain, signed, and unsigned).

like image 132
Cameron Avatar answered Dec 08 '25 20:12

Cameron


When you assign a negative value to an unsigned variable, the result is that it wraps around. -1 becomes 255 in this case.

like image 30
Vaughn Cato Avatar answered Dec 08 '25 20:12

Vaughn Cato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!