Javascript
a == a +1
In Javascript, there are no integers but only Number
s, which are implemented as double precision floating point number.
It means that if a Number a
is large enough, it can be considered equal to 3 consecutive integers:
a = 100000000000000000
if (a == a+1 && a == a+2 && a == a+3){
console.log("Precision loss!");
}
True, it's not exactly what the interviewer asked (it doesn't work with a=0
), but it doesn't involve any trick with hidden functions or operator overloading.
Other languages
For reference, there are a==1 && a==2 && a==3
solutions in Ruby and Python. With a slight modification, it's also possible in Java.
Ruby
With a custom ==
:
class A
def ==(o)
true
end
end
a = A.new
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
or an increasing a
:
def a
@a ||= 0
@a += 1
end
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Python
class A:
def __eq__(self, who_cares):
return True
a = A()
if a == 1 and a == 2 and a == 3:
print("Don't do that!")
Java
It's possible to modify Java Integer
cache. They're not primitive int
s though, so Integer.valueOf(1)
has to be used instead of just 1
:
package stackoverflow;
import java.lang.reflect.Field;
public class IntegerMess
{
public static void main(String[] args) throws Exception {
Field valueField = Integer.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.setInt(1, valueField.getInt(42));
valueField.setInt(2, valueField.getInt(42));
valueField.setInt(3, valueField.getInt(42));
valueField.setAccessible(false);
int a = 42;
if (a == Integer.valueOf(1) && a == Integer.valueOf(2) && a == Integer.valueOf(3)) {
System.out.println("Bad idea.");
}
}
}