</>EmbeddedInterview

What happens when you compare signed and unsigned integers?

MediumC Programming

Short answer: If the two operands have the same rank (e.g. int and unsigned int), the usual arithmetic conversions convert the signed one to unsigned. A negative number becomes a very large positive one, so comparisons give the "wrong" answer.

int i = -1;
unsigned int u = 1;
if (i < u) puts("less");       /* not printed: -1 becomes 0xFFFFFFFF */

if (-1 < sizeof(int)) puts("yes");   /* not printed: sizeof is size_t (unsigned) */

for (unsigned i = 10; i >= 0; i--) { }   /* infinite loop: unsigned is always >= 0 */

size_t len = strlen(s);
if (len - 1 >= 0) { }          /* always true; if len is 0, len - 1 wraps to SIZE_MAX */

When it does not happen: if the signed type is wider and can represent all values of the unsigned one, the unsigned operand is converted to the signed type instead. long long x = -1; unsigned int u = 1; x < u is true, because u becomes long long. Small types (uint8_t, uint16_t) are promoted to int first, so int8_t a = -1; uint8_t b = 1; a < b is true.

How to avoid it

  • Compile with -Wall -Wextra (which includes -Wsign-compare) and fix every warning.
  • Use one signedness consistently for sizes and indexes (size_t), and check for negative values before converting signed to unsigned.
  • Compare explicitly: if (i < 0 || (unsigned)i < u).
  • For "count down to zero" with unsigned indices, use for (size_t i = n; i-- > 0; ).

C23 adds checked-arithmetic helpers (ckd_add, ckd_sub, ckd_mul in <stdckdint.h>), and GCC/Clang have __builtin_add_overflow for overflow-safe arithmetic.