Where is unsigned char used in C ( please tell about some real-world examples )?
Why would we need both char and unsigned char?
signed
or unsigned
are properties of the different C data types (char
, short
, int
, etc...). So it's not a question of whether we need both, both come automatically as part of how C is defined.
Char ranges from -127 to 128 ( 8-bit integer ) Unsigned Char ranges from 0 to 255 ( 8-bit integer )
While that's true for most of the platforms out there, there's nothing garanting that char
will be signed. In fact on ARM platforms, it's unsigned
. See this fix: http://www.spinics.net/lists/linux-btrfs/msg20653.html as an example of real-world bug introduced by assuming that char
is signed.
If the purpose is to store ASCII, why would we need both?
The thing is, the purpose is not to store ASCII. It happens to be used to store ASCII but it's a not a necessity.
char a = 127;
unsigned char b = 255;
When I print it using std::cout. It gives me different characters. Can you explain why? ( I'm using Microsoft vs11 compiler
I think what you're looking for is the following:
#include <iostream>
int main(void)
{
char a = -1;
unsigned char b = 255;
std::cout << a << std::endl << b << std::endl;
return 0;
}
That is '-1' signed
will be equal to '255' unsigned
. Please note that this is heavily implementation dependent, and there's nothing that guarantees it will work accross all platforms and compilers.
reinterpret_cast<const char *>
.