What will be the value of m-n where m,n are unsigned char and m=1 and n=255 in C?

what is output of this c program ,int main { unsigned char m=1,n=255; printf(“%d”,m-n); }

✅ Answers

? Best Answer

  • To keep things simple, let’s assume a char is eight bits wide, so your two values are 01 (0x01) and 11111111 (0xFF). just doing the subtraction by hand and keeping the result to 8 bits you get 10 (0x02).

    Because this is an unsigned char it looks like the result is two. But don’t forget, the subtraction actually generated a carry that propogates off to the left, so the actual result is more like 0xFFFFFFFFFFFFFF02 if we presume 64 bit operands. But because we’re dealing with unsigned chars, we only keep the right most 8 bits.

    Also worth noticing is that using only 8 bits, if you add 254 (decimal) to 0x02 you get zero. So 0x02 can be considered as equal to -254, which after all is what the correct signed result of the original subtraction is. This gives us the true nature of signed and unsigned chars/ints in C.

    -254 (signed) = +2 (unsigned)
    -128(signed) = +128 (unsigned) <== Just the top bit set

  • Compile it, run it and find out. You don’t need to waste time asking questions like this.

  • Leave a Comment