Tuesday, 18 September 2012

Puzzle 30: Son of Looper


Provide a declaration for i that turns this loop into an infinite loop:
while (i != i + 0) {

}


Unlike previous loopers, you must not use floating-point in your answer. In other words, you must not declare i to be of type double or float.

Solution 30: Son of Looper

Like the previous puzzle, this one seems impossible at first glance. After all, a number is always equal to itself plus 0, and you were forbidden from using floating-point, so you can't use NaN. There is no NaN equivalent for the integral types. What gives?
The inescapable conclusion is that the type of i must be non-numeric, and therein lies the solution. The only non-numeric type for which the + operator is defined is String. The + operator is overloaded: For the String type, it performs not addition but string concatenation. If one operand in the concatenation is of some type other than String, that operand is converted to a string prior to concatenation [JLS 15.18.1].
In fact, i can be initialized to any value so long as it is of type String; for example:
String i = "Buy seventeen copies of Effective Java!";


The int value 0 is converted to the String value "0" and appended to the blatant plug. The resulting string is not equal to the original as computed by the equals method, so it certainly can't be identical, as computed by the == operator. Therefore, the boolean expression (i != i + 0) evaluates to TRue and the loop never terminates.
In summary, operator overloading can be very misleading. The plus sign in the puzzle looks like addition, but it is made to perform string concatenation by choosing the correct type for the variable i, which is String. The puzzle is made even more misleading because the variable is named i, a name that is usually reserved for integer variables. Good variable, method, and class names are at least as important to program readability as good comments.
The lesson for language designers is the same as in Puzzles 11 and 13. Operator overloading can be confusing. Perhaps the + operator should not have been overloaded for string concatenation. It may well be worth providing a string concatenation operator, but it doesn't have to be +.

No comments:

Post a Comment

Your comments are welcome!