Mixing signed and unsigned in math
What you'll learn: Why comparing signed and unsigned numbers can lead to surprising results due to C's conversion rules.
The Secret Promotion
In C, when you perform math or a comparison between a signed integer (int) and an unsigned integer (unsigned int), the computer doesn't just average the difference. Instead, it follows a rule called "Usual Arithmetic Conversions." The most important rule to remember is: Unsigned wins.
If you mix the two types, C temporarily converts the signed value into an unsigned value. While this sounds harmless, it creates a massive "logic trap" when dealing with negative numbers.
The "Huge Number" Illusion
Imagine you have a debt of -5 dollars (signed) and a savings of 10 dollars (unsigned). In basic math, -5 is clearly less than 10. However, in C, the negative sign is just a bit pattern.
When a negative signed integer is converted to unsigned, that negative sign (the leftmost bit) is reinterpreted as a very large value. A small negative number like -1 suddenly transforms into the largest possible number the variable can hold (like 4,294,967,295).
See it in action
Look at how this comparison fails in a real program:
#include <stdio.h>
int main() {
int temperature = -5; // Signed: can be negative
unsigned int limit = 10; // Unsigned: always positive
if (temperature < limit) {
printf("It is cold!\n");
} else {
printf("Wait, -5 is greater than 10?\n");
}
return 0;
}
If you run this, C converts -5 to a massive unsigned integer to match the type of limit. Because 4 billion is greater than 10, the program will tell you that -5 is actually larger! This is a common source of bugs in security checks and loops.
How to stay safe
To avoid these headaches, try to keep your types consistent. If you must compare them, "cast" them manually so they are both the same type, or ensure your signed variable isn't negative before the comparison.
Key takeaway
When signed and unsigned meet, C treats the signed number as unsigned, turning negative values into giant positive ones.