Code Quickie: What's in my char?

Have you ever wondered why certain types like char, int, float, ect. can hold certain values? For example, a char can hold values between -127 and 128 or between 0 and 255 depending on whether it can hold negative values or not. Letters and characters (or any data) each have a corresponding numerical value, so the values themselves are not limited to numbers, but the numerical representation is still restricted.

All types in any programming language have a size in bytes, where each byte consists of 8 bits. The size of a type can depend on the implementation of the language but you can always check what it is. However a char is always 1 byte, so let's use that as an example. Why can a char hold 256 values in it (-127 - 128 or 0 - 255)? The answer is binary. Our 1 byte char consists of 8 bits, and each bit can contain either a 0 or a 1, representing true or false, or representing digits in the binary representation of a number. With 8 1's or 0's at our disposal, the maximum number we can represent is 11111111, which is the binary representation for 256, which can also be written as 28.  

This can be extended to any type, so a 2 byte type can hold 16 bits, giving 65536 different values, a 4 byte type can hold 32 bits which is 4294967296, etc. Overflow happens when you try and assign a type to a value outside the range determined by it's size. So setting a char equal to 256 would cause an overflow, and lead to unexpected behaviour. One outcome is that the value "wraps around", similar to modular arithmetic, and you may actually get back 1 instead of 256.

It is useful to be mindful when choosing what type to use and consider it's size. What are you assigning to the variable and what do you expect the max and min values to be. Also ensure that overflow doesn't happen, or at least that it is handled when it does.