If we were writing C++ from scratch in 2016, maybe we would make this work. However as it choose to be (mostly) backward compatible with a fairly low level language like C, 'char'
is in fact just a number, that string/printing algorithms interpret as a character -but most of the language doesn't treat special. Including the cast. So by doing (char)
you're only converting a 32 bit signed number (int
) to a 8 bit signed number (char
).
Then you interpret it as a character when you print it, since printing functions do treat it special. But the value it gets printed to is not '5'
. The correspondence is conventional and completely arbitrary; the first numbers were reserved to special codes which are probably obsolete by now. As Hoffman pointed out, the bit value 5
is the code for Enquiry
(whatever it means), while to print '5'
the character has to contain the value 53
. To print a proper space you'd need to enter 32
. It has no meaning other than someone decided this was as good as anything, sometime decades ago, and the convention stuck.
If you need to know for other characters and values, what you need is an "ASCII table". Just google it, you'll find plenty.
You'll notice that numbers and letters of the same case are next to each other in the order you expect, so there is some logic to it at least. Beware, however, it's often not intuitive anyway: uppercase letters are before lowercase ones for instance, so 'A' < 'a'
.
I guess you're starting to see why it's better to rely on dedicated system functions for strings!