125. Identify Trap in Signed vs Unsigned Comparison

Back To All Submissions
Previous Submission
Next Submission

Code

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

int safe_compare(int8_t a, uint8_t b) {
    // Trap : Comparing signed vs unsigned variables
    // What happens : Signed -> Unsigned
    // I.e value assigned to a signed int (-127 to 127) outside of this range will be converted to an uint8
    //printf("A Uncast %d\n",a);
    //printf("A cast %d\n",(uint8_t)a);
    //If the signed int < 0 then its negative and has to be smaller than b by defition
    if(a < 0){
        return 1;
    }
    //Cast the positive numbers of the signed int to an unsigned int
    else 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;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote