Signed vs Unsigned Integer Comparison Gotcha in C

This one looks obvious… until it isn’t 👇 int i = -3; unsigned int j = 5; printf("%d\n", i < j); What would you expect this to print? Most people would say 1 (true). But the actual output is: 0 So what’s going on here? It comes down to how C handles comparisons between signed and unsigned integers. When i (which is -3) is compared with an unsigned value, it doesn’t stay negative. Instead, it gets implicitly converted to an unsigned integer. That transformation turns -3 into a very large positive number (on a 32-bit system, it becomes 4294967293). So the comparison the compiler actually performs is: 4294967293 < 5 → false Why this matters: This kind of implicit conversion is subtle and easy to miss, but it can introduce serious bugs — especially in: • Embedded systems • Kernel / low-level code • Boundary checks and loop conditions It’s one of those cases where the code looks right, compiles fine, and still behaves unexpectedly. Have you run into bugs caused by signed vs unsigned mismatches? #cprogramming #embeddedc #systemsprogramming #lowlevel #debugging #codingpitfalls #softwareengineering #linux #cplusplus #techinsights

  • diagram

To view or add a comment, sign in

Explore content categories