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
    // Cast both to 16-bit to avoid the signed/unsigned promotion trap
    // and to prevent 8-bit overflow.
    int16_t promoted_a = (int16_t)a;
    int16_t promoted_b = (int16_t)b;
    
    return promoted_a + promoted_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