126. Add Signed and Unsigned Integers Safely

Back To All Submissions
Previous Submission
Next Submission

Code

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

int16_t signed_unsigned_sum(int8_t a, uint8_t b) {
    // Your logic here
    /*
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.
    */
    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;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote