basics · beginner · ~10 min

Spot the signed/unsigned compare trap

Recognize implicit conversion in signed/unsigned compares.

Challenge

Implement int safer_lt(int a, size_t b) returning 1 if a < b is true in the mathematical sense (treating a as signed and b as unsigned but with negative a always meaning 'less than any nonneg b'), else 0.

In plain if (a < b) C promotes a to size_t, turning -1 into SIZE_MAX. The safer version checks the sign first.

Why this matters

if (signed_var < unsigned_var) triggers implicit conversion that flips negative numbers to huge positives. Real-world CVEs (e.g. in mmap-size validation) come from this.

Input format

signed int, unsigned size_t.

Output format

0 or 1.

Constraints

No casts that hide the rule.

Starter code

#include <stddef.h>
int safer_lt(int a, size_t b) { /* TODO */ return 0; }

Common mistakes

Writing the naïve return a < b; and not catching that -1 < (size_t)5 evaluates false because (size_t)-1 == SIZE_MAX.

Edge cases to handle

a == INT_MIN; a == 0, b == 0; large b near SIZE_MAX.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.