LOGBOOK

HELP

Quiz Entry - updated: 2026.07.14

How does C handle mixing signed and unsigned types in expressions?

In any expression that mixes signed and unsigned operands — including comparisons — the signed operand is implicitly converted to unsigned, which flips many "obvious" comparisons.

Explicit casting:

int tx, ty;
unsigned ux, uy;

// Explicit: unsigned → signed
tx = (int) ux;
// Explicit: signed → unsigned
uy = (unsigned) ty;

Implicit casting (the dangerous kind):

// Implicit conversion - same bit pattern, different interpretation
tx = ux;
// If ty is negative, becomes huge positive!
uy = ty;

The danger with comparisons:

Expression Result Why
0 == 0U 1 (true) Both zero
-1 < 0 1 (true) Signed comparison
-1 < 0U 0 (false)! -1 becomes UINT_MAX
2147483647 > -2147483647-1 1 (true) Signed comparison
2147483647U > -2147483647-1 0 (false)! RHS becomes huge
-1 > -2 1 (true) Signed comparison
(unsigned)-1 > -2 1 (true) Both converted to unsigned

The rule: If one operand is unsigned, the other is converted to unsigned.

Real-world bug (from earlier card):

int copy_from_kernel(void *dest, int maxlen) {
    int len = maxlen > KSIZE ? KSIZE : maxlen;
    // len=-1 becomes 4GB!
    memcpy(dest, kbuf, len);
}

Best practice: Don't mix signed and unsigned. Use -Wall -Wextra to catch warnings.

Go deeper:

From Quiz: REVE1 / C Programming | Updated: Jul 14, 2026