Signed vs. Unsigned chars
What you'll learn: How the signed and unsigned keywords change the way a character variable interprets numeric values.
In C, a char is just a tiny box in memory that holds 8 bits (1 byte) of data. While we usually use them to store letters like 'A' or '!', the computer sees them as numbers. By default, a char can be treated as either "signed" or "unsigned," and the difference determines the range of numbers that box can hold.
The Number Line Analogy
Imagine you have a small ruler that is exactly 256 millimeters long.
An unsigned char is like starting your ruler at 0. You can measure anything from 0 up to 255. It’s perfect for things that can never be negative, like the brightness of a pixel or a raw byte of data.
A signed char, however, shifts that ruler. Instead of starting at 0, it places 0 right in the middle. You can now measure "negative" space. It covers a range from -128 to 127. Notice that both types still hold exactly 256 unique values; they just label those values differently.
Why Does It Matter?
If you store the number 200 in an unsigned char, it stays 200. But if you try to store 200 in a signed char, the computer gets confused because 200 is outside its maximum limit of 127. The bits "wrap around," and you might end up with a negative number like -56.
In the ASCII table, standard characters only go up to 127, so both types work fine for basic English text. However, if you are working with extended characters or raw math, you must choose carefully.
Code Example
Here is how they look in action:
#include <stdio.h>
int main() {
// Both occupy 1 byte of memory
unsigned char positiveOnly = 200;
signed char canBeNegative = -50;
printf("Unsigned value: %d\n", positiveOnly);
printf("Signed value: %d\n", canBeNegative);
// Watch what happens if we go over the signed limit
signed char overflow = 130;
printf("Overflow result: %d\n", overflow); // Likely prints -126
return 0;
}
When you write char without a prefix, your compiler decides if it is signed or unsigned by default. If you need to guarantee a specific range for math, always be explicit by typing the full name.
Key takeaway
An unsigned char stores 0 to 255, while a signed char stores -128 to 127; both use the same 8-bit space but interpret the data differently.