Detect Underflow in Unsigned Subtraction

Code

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

int main()
{
    uint8_t a, b;
    uint8_t diff;
    uint8_t carry;  

    scanf("%hhu %hhu", &a, &b);
    
    
    if (b>a) {
        diff=-(a-b);
        diff=256-diff;
        carry =1;
    }
    else {
        diff=a-b;
        carry=0;
    }
    printf("diff = %d, carry = %d",diff,carry);
  
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

100 50

Expected Output

diff = 50, carry = 0