Let's examine Add
and Multiply
as examples. Which one can be categorized as widening?
Assume inputs are signed characters (i.e 8 bits in length) in 2's complement, unless declared otherwise.
Positive number addition
1+2 = 3
This operation doesn't seem to be widening. 1, 2 and 3 all fit in a character.
However, 250 + 6
overflows an unsigned char. So is this widening?
Same could be done with signed type, 125 + 5
overflows signed char into the sign bit. Is this widening?
Negative number addition
-2-3 = -5
This overflows a character in binary by 1 bit:
1 1 1 1 1 1 1 0
+ 1 1 1 1 1 1 0 1
------------------
1 1 1 1 1 1 0 1 1
The overflow is normally discarded, however, is this considered a widening operation?
Positive number multiplication
1 * 2 = 2
Are all multiplications widening, even if the result still fits in the original data type?
The above example, 2
still fits in an 8-bit character however, if I do the math by hand in binary, extra 0s
get appended to left of the result which get discarded.
Negative number multiplication
-2 * -3 = 6
For simplicity, let's assume our inputs are 4 bits. This overflows by twice its size as expected, i.e the result becomes 8 bits:
1110 * 1101 = 10110110
The upper 4 bits are discarded and the lower 4 bits equal 6
as expected.
Is this considered a widening operation?
Division
I haven't gone into detail about division but I assume it's considered a narrowing operation.