I read that one can use "char" for small integers. However, when I try,
unsigned char A = 4;
std::cout << A << std::endl;
it gives a character, not 4.
What you are experiencing are the effects of operator overloading. The <<
operator assumes that you most likely want to print a character when you hand it a variable of type char
, therefore it behaves differently than you would expect it for integral variables.
As suggested by Vivek Goel you can force the compiler to select the overload you actually want:
unsigned char a = 4;
std::cout << static_cast<unsigned int>(a) << std::endl;
// or
std::cout << unsigned{a} << std::endl;
Addendum: Unless you are working on an environment with severely constrained resources (esp. tiny memory), you are optimising on the wrong end. Operations on unsigned int
are typically faster than on unsigned char
, because your processor cannot fetch single bytes but has to get at least a multiple of 4 and mask out the other 3 bytes.