# Comparisons between signed and unsigned numbers.

Q5. Why should following operations be discouraged?

1. comparisons between two floating point numbers
2. comparisons between signed and unsigned numbers.

Ans.(1). Avoid equality comparisons on floating-point numbers.

Floating-point arithmetic is not as exact and accurate as the integer arithmetic is.

For instance, 3*5 is exactly 15, but 3.25*5.25 is nearly equal to 17.06 (if we are working with number with 2 decimal places). The exact number resulting from 3.25*5.25 is 17.0625. Therefore, after any calculation involving floating-point numbers, there may be a small residue error. Because of this error, you should avoid the equality and inequality comparisons on floating-point number.

Ans.(2). Avoid comparing signed and unsigned values.

It is because if you compare a signed value with an unsigned value, the compiler will treat the signed value as unsigned. If the signed value is negative, it will be treated as an unsigned integer having the same bit pattern as the signed value, and the result of the comparison will be arbitrary. To understand this more clearly, let us consider following example (we are considering 4-bit code for the sake of simplicity):

If we have the expression

A<b

(if a = 3 and b = -4)

then the expected result should be 0 as 3>-4 but the produced result will be 1. Just because the bit pattern for -4 (1100 where left most 1 signals it is negative and rest of the bit pattern 100 is the binary equivalent of 4) is treated as unsigned integer (that is, left most bit is no more considered as sign bit) and the equivalent integer of 1100 is 12. Thus the expression a<b is treated as 3<12 which results into true that is, 1. Therefore, the comparison between signed and unsigned values should be avoided.

105 Views