When to choose unsigned over signed
What you'll learn: How to decide between signed and unsigned types based on whether your data represents a physical quantity or a mathematical coordinate.
In C, choosing between int (signed) and unsigned int isn't just about how large a number you can store. It is about defining the "rules" of your data. If you pick the wrong one, your program might behave in strange ways when numbers get very large or very small.
The "Absolute Zero" Rule
The simplest way to decide is to ask: "Does a negative value make sense in the real world for this specific thing?"
Think of a signed integer like a thermometer. Temperature can be , but it can also be . The zero point is just a marker on a scale, and numbers can live on either side of it.
Think of an unsigned integer like a tape measure. You can have a piece of wood that is 10cm long, or 0cm long, but you can never have a piece of wood that is -5cm long. Length, age, file sizes, and pixel coordinates are "unsigned" by nature. They start at zero and only go up.
Memory and Safety
When you use unsigned, you tell the computer, "I promise this number will never be negative." In exchange, the computer gives you double the positive range. For example, a 16-bit signed integer goes up to 32,767. An unsigned one goes up to 65,535.
However, be careful! If you subtract 5 from an unsigned 0, it doesn't become -5. Instead, it "wraps around" to the largest possible number the type can hold, which can cause massive bugs.
Example: Choosing the right type
Here is how you might apply this logic in a real program:
// Example: Tracking player stats in a game
// Life can never be negative; 0 means the player is dead.
unsigned int health_points = 100;
// The number of items in a backpack cannot be negative.
unsigned int inventory_count = 5;
// The change in score could be negative (a penalty).
int score_change = -50;
// A coordinate on a map might be North (+) or South (-) of the equator.
int latitude = -22;
Generally, use int (signed) as your default choice for math to avoid accidental wrap-around errors. Switch to unsigned only when you are representing a count, a size, or a bit-pattern where a negative value is physically impossible.
Key takeaway
Use unsigned types for quantities that have a natural "floor" at zero, like sizes or counts, and signed types for anything that can fluctuate above and below a starting point.