67. Identify Trap in Signed vs Unsigned Comparison

#include <stdio.h>
#include <stdint.h>

int safe_compare(int8_t a, uint8_t b) {
    if (a < 0) {
        return 1;  // Any negative number is less than any uint8_t
    }
    return (uint8_t)a < b;
}

int main() {
    int8_t a;
    uint8_t b;
    scanf("%hhd %hhu", &a, &b);
    printf("%d", safe_compare(a, b));
    return 0;
}

What is the trap here?

When comparing int8_t a = -1; and uint8_t b = 1;,

the compiler promotes a to uint8_t, which becomes 255, so 255 < 1 becomes false — this is the trap.

Why it matters in firmware?

  • Sensor values, register flags, buffer sizes — mixing signed/unsigned is common
  • Mistakes here can cause faulty condition checks, loops, and bugs that are hard to trace

Solution Logic

  • If a < 0, then clearly a < b regardless of b
  • Else, safely cast a to uint8_t and compare


     
Loading...

Input

-1 1

Expected Output

1