#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?
Solution Logic
Input
-1 1
Expected Output
1