Quiz Entry - updated: 2026.07.07
What happens when you assign a small signed value to a larger unsigned type?
The value is sign-extended to the wider size first, then reinterpreted as unsigned — so a small negative like −1 becomes a huge positive.
signed char sc = -1; // 0xFF (8 bits)
// Sign-extend to 0xFFFFFFFF = -1
int i = sc;
// Sign-extend, then interpret as unsigned!
unsigned int ui = sc;
// 0xFFFFFFFF = 4,294,967,295 !
The sequence:
signed char(-1) =0xFF- Sign-extend to
int:0xFFFFFFFF= -1 - Interpret as
unsigned int:0xFFFFFFFF= 4,294,967,295
Why this is dangerous:
// Returns -1 on error
signed char len = get_length();
// If buffer_size is unsigned...
if (len < buffer_size) {
// -1 becomes HUGE positive, comparison passes!
// Potential buffer overflow!
}
Safe pattern:
signed char len = get_length();
// Check negative FIRST
if (len < 0) return ERROR;
// Now safe to compare
if ((size_t)len < buffer_size) {
// ...
}
Tip: Be especially careful with char - it's signed on most systems but can hold values 0-255 from files!