Saturday 3 September 2022

The Good Old Variable Swap, Redux

Some time back, I wrote a short piece, a how-to on the classic variable swap. Today is a good time to revisit that. As with the last time, code samples are in QBasic.

I was demonstrating this in a class, and one of the students had this bright idea: would this method work with multiplication and division, instead of addition and subtraction?

His idea was as follows.
DIM a = 3
DIM b = 2

a = a * b
b = a / b
a = a / b


And my answer was an unequivocal no. This is why.

In his example, a was 3 and b was 2. That would work. But consider this: what if either a or b was 0? Let's try both times.

Example 1: a = 0, b = 2
DIM a = 0
DIM b = 2

'a = 0 * 2 = 0
a = a * b

'b = 0 / 2 = 0
b = a / b

'a = 0 / 0
a = a / b


Example 2: a = 3, b = 0
DIM a = 3
DIM b = 0

'a = 3 * 0 = 0
a = a * b

'b = 0 / 0
b = a / b

a = a / b


In either case, at some point we are going to end up in a scenario where a division by zero would be attempted. And as we all know, once a division by zero is attempted, an exception occurs.

The dreaded zero.

We could get around this limitation by doing a Try-catch, and assuming the value of 0 once the exception is thrown. But that would add a level of complexity to what is supposed to be a very simple formula.

The takeaway

It was a nice try, and I like to encourage that. An experimental and curious mindset is always valuable to a programmer. What's important is that we always bear certain basics in mind.

Happy pr0gramming,
T___T

No comments:

Post a Comment