i m a beginner in C++. I have some questions:
what is static_cast<unsigned>?
i saw someone use static_cast<unsigned> and static_cast<unsigned char>
together. why?
e.g. static_cast<unsigned>(static_cast<unsigned char>(c))
(c is a char).
Take an implementation where char ranges from -128 to 127, the cast
from char to unsigned char (on this implementation) converts it to the
range 0 to 255 and then the cast to unsigned int leaves it in that 0 to
255 range. Without the unsigned char cast there, converting the char to
an unsigned integer directly (lets say unsigned int ranges from 0 to
0xFFFF on this implementation) would convert it to either 0 to 127 if c
is positive or 0xFFFF+1-128 to 0xFFFF+1-1 if c is negative (all these
ranges here are inclusive).
So basically, it's because char isn't guaranteed to be signed or
unsigned, so we want to force it to become unsigned.
If the code is doing what I think it's trying to do, it's wrong in
general (but works on the majority of 2s complement computers, which is
why you see it in the wild). The correct way is static_cast<const
unsigned char&>(c) because you want to cast the bits of the character
and not the mathematical value of it.