Quiz Entry - updated: 2026.07.14
What are the dangers of mixing signed and unsigned comparisons in C?
When you compare a signed and an unsigned value, C converts the signed one to unsigned first — so a negative number becomes huge and the comparison flips.
| Expression | Type | Evaluation |
|---|---|---|
-1 < 0 |
signed | TRUE ✓ |
-1 < 0U |
unsigned | FALSE ✗ |
2147483647 > -2147483647-1 |
signed | TRUE ✓ |
2147483647U > -2147483647-1 |
unsigned | FALSE ✗ |
What happens with -1 < 0U:
-1 < 0U
// -1 is converted to unsigned first!
// -1 as unsigned 32-bit = 0xFFFFFFFF = 4,294,967,295
// FALSE!
4294967295 < 0
Real-world vulnerability pattern:
// Attacker sends -1
int len = get_user_input();
// sizeof returns size_t (unsigned)!
if (len < sizeof(buffer)) {
// -1 becomes HUGE positive, comparison passes!
// Buffer overflow!
memcpy(dest, src, len);
}
Rule: When comparing signed and unsigned, the signed value is converted to unsigned.
How to protect yourself:
- Use
-Wall -Wextra- compiler warns about signed/unsigned comparisons - Cast explicitly:
if ((size_t)len < sizeof(buffer)) - Check for negative first:
if (len >= 0 && (size_t)len < sizeof(buffer)) - Use
size_tfor sizes consistently
Tip: The U suffix matters! 0 is signed, 0U is unsigned. This affects the whole comparison.