C/C++ Arena

Step 5 of 7

The signed/unsigned comparison trap

When you compare a signed int with an unsigned value like size_t (what strlen and sizeof return), C converts the int to unsigned first. A negative int becomes a huge positive number:

int n = -1;
if (strlen("abc") > n)   // false! -1 becomes 18446744073709551615 (or 4294967295)

-Wall -Wextra warns about this (-Wsign-compare). Treat that warning as a bug report, not noise.

Your turn: longer_than(s, n) should return 1 when s has more than n characters. It's wrong for negative n (every string is longer than -1 characters). Fix it without casting the length to int (strings can be longer than INT_MAX).

Previous: Fixed-width types Next: Floating-point rounding