68. Add Signed and Unsigned Integers Safely

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

int16_t signed_unsigned_sum(int8_t a, uint8_t b) {
    // Convert both to int16_t to avoid promotion trap
    return (int16_t)a + (int16_t)b;
}

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

What’s the issue?

In C, if a is negative and b is unsigned, a gets promoted to unsigned before addition, leading to unexpected results.

Example: -1 (int8_t) + 1 (uint8_t) becomes 255 + 1 = 256 if promoted incorrectly.

Why it matters in firmware?

  • Timers, buffer indexes, counters — mixing signed and unsigned is common
  • Avoiding implicit conversion bugs is critical for reliability

Solution Logic

  • Cast both a and b to int16_t explicitly before adding
  • Prevents unsigned overflow from negative signed values

 

Loading...

Input

-10 20

Expected Output

10