All submissions

Identify Trap in Signed vs Unsigned Comparison

Code

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

int safe_compare(int8_t a, uint8_t b) 
{
    if(!(a>=-128 && a<=127)) //-128 -127 to +127
      a=a-256;
      
    return a<b; //this instruction will automatically check and return 1 if it is true. Else it will return 0.
}

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

Solving Approach

1: Range of signed char: -128 to +127

2: If the value of a is not lying in above range, then we need to adjust it such that it comes into that range.

3: Once value of a is brought into the range, we need to compare and return the value.

 

 

 

Loading...

Input

-1 1

Expected Output

1