66. Detect Underflow in Unsigned Subtraction

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

void subtract_with_underflow(uint8_t a, uint8_t b, uint8_t *diff, uint8_t *carry) {
    *diff = a - b;
    *carry = (b > a) ? 1 : 0; // If b > a, subtraction wraps around
}

int main() {
    uint8_t a, b, diff, carry;
    scanf("%hhu %hhu", &a, &b);
    subtract_with_underflow(a, b, &diff, &carry);
    printf("diff = %u, carry = %u", diff, carry);
    return 0;
}

Unsigned types like uint8_t wrap around when underflow occurs.

For example: 10 - 20 = 246 because -10 wraps around modulo 256.

Why it matters in firmware?

  • Many counters and hardware registers are unsigned
  • Detecting underflow is important for bounds checks, timers, buffer logic
  • Prevents unexpected behavior from wrap-around

Solution logic

  • Direct subtraction using a - b
  • Use comparison b > a to detect underflow
     
Loading...

Input

100 50

Expected Output

diff = 50, carry = 0