90
votes
\$\begingroup\$

The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

  1. Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.
  2. Simple - should be small, use basic language features.
  3. Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.
  4. Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

  1. The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.
  2. Floating point. Large numbers, infinity or NaN all work.
  3. Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

    The rest don't work with C:

  4. Operator overloading - A + that doesn't add or a == that always returns true.
  5. Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.
  6. A one-bit data type. Then x == x+2 (mod 2).
  7. Changing 2 - some language let you assign 0 to it.
\$\endgroup\$
  • 29
    \$\begingroup\$ Why 4. Quick? You mean "Whoever knows one and is lucky enough to read this question first"? \$\endgroup\$ – Luc Sep 7 '12 at 21:43
  • 6
    \$\begingroup\$ @ugoren Let the community vote (and vote yourself for ones you like), then choose the top answer after 7 days or so :) \$\endgroup\$ – Luc Sep 8 '12 at 21:48
  • 3
    \$\begingroup\$ Regarding possibility 2: NaN doesn't work. NaN+2 is again NaN, but NaN==NaN is false. \$\endgroup\$ – Martin B Oct 26 '12 at 13:51
  • 2
    \$\begingroup\$ The Scala solution, where x is a Set containing '2', and + means add to Set by the standard library, without redefining + yourself, doesn't fit into these 7 categories, IMHO. \$\endgroup\$ – user unknown Dec 19 '12 at 21:20
  • 2
    \$\begingroup\$ Why are this question and all the answers Community Wiki? \$\endgroup\$ – mbomb007 Jul 2 '15 at 18:49

98 Answers 98

1
vote
\$\begingroup\$

Scheme / Unicode

(let
  ((2 0) (x 9))
  (= x (+ x 2)))

I knew there had to be a Unicode character that looks like a 2 - and that there would be a language or interpreter lenient enough to accept it as a variable name.

\$\endgroup\$
1
vote
\$\begingroup\$

ECMAScript (also known as JavaScript):

x=1e17
\$\endgroup\$
1
vote
\$\begingroup\$

Haskell, denotational semantics

x = undefined

As most of you probably know, undefined :: a can be cast to any type - or in other words, every type contains a special value undefined, also called (pronounced "bottom"). We say that is less defined than any other inhabitant of that type, and while its a little too in-depth for this post, can also be seen as a computation that never finishes.

Let's import Data.Function.

In there, there is a function called fix, which according to the Haskell docs finds the least-defined fixpoint of f, by repeatedly applying the function to itself. Let's recap:

We need to find a value x, for which x = x + 2, or, equivalently x = (+2) x. Lets factor (+2) into a function called f. We get x = f x, which is precisely the definition of a fixed point for the function f. Since we don't know x yet, we need a function that knows how to calculate a fixpoint, like fix; x is our placeholder for said fixpoint (x = fix f), so our whole equation becomes fix f = f (fix f).

This is just the definition of fix, so fix indeed finds a fixed point for a given function!

What I'm trying to say is: To solve OP's problem, all we need to do is pipe fix (+2) through ghci. When we do that however, we see nothing, as ghci gets caught in an infinite loop. But since I said that infinite loops can be seen as ⊥, we arrive at the fact that x = ⊥, which by the way turns out to be the only solution to OP's question (who would have guessed).

\$\endgroup\$
1
vote
\$\begingroup\$

Python 2.7, 46 chars

I see a lot of Python answers abusing real number limitations, I'm surprised no one's submitted this disgusting Python hack yet.

x=True;True=False;
if True is (x==x+2): print x

Returns:

True
\$\endgroup\$
1
vote
\$\begingroup\$

PHP

$isi = 1.0E+17;
var_dump($isi == $isi + 2);

$isi = 1e18;
var_dump($isi == $isi + 2);

$isi = 4.2E+20;
var_dump($isi == $isi + 2);

$isi = 9.2233720368548E+18;
var_dump($isi == $isi + 2);

$isi = 5.0E+19;
var_dump($isi == $isi + 2);

$isi = 6.0822444802213E+18;
var_dump($isi == $isi + 2);

$isi = 0x5468792130ABCDEF;
var_dump($isi == $isi + 2);

$isi = 6082244480221302255;
var_dump($isi == $isi + 2);
\$\endgroup\$
0
votes
\$\begingroup\$

the answer is infinity or - infinity because infinity+2=infinity you can't find any other number that it's bigger than itself+ a number

\$\endgroup\$
  • \$\begingroup\$ Infinity is an answer, but not the only one (as you can see here). \$\endgroup\$ – ugoren Sep 7 '12 at 8:14
0
votes
\$\begingroup\$

Ruby

1.9.3p125 :006 > x = Float::INFINITY  # or x = -Float::INFINITY
 => Infinity 
1.9.3p125 :007 > x == x +2
 => true 



1.9.3p125 :015 > x =Float::MAX
 => 1.7976931348623157e+308 
1.9.3p125 :016 > x == x +2
 => true 
\$\endgroup\$
0
votes
\$\begingroup\$

In Scala, just override the "+" operator (really a function):

scala> class X { def +(a:Int)=this }
defined class X

scala> val x = new X
x: X = X@26e7127

scala> x == x+2
res3: Boolean = true

scala> 
\$\endgroup\$
0
votes
\$\begingroup\$

Ruby

That's surely cheating, but hey ...

#/usr/bin/env

class Fixnum
  def +(y)
    if self == 42
       self
    else
       self + y
    end
  end
end

Then for x being exactly 42 ... /me => [ ]

\$\endgroup\$
0
votes
\$\begingroup\$

Javascript

Most compact, correct that I could figure.

x=1/0;x==x+2

I also tried futzin around with toString() and clever output variance with casting, but while the results were correct sequentially, the == would never be true.

\$\endgroup\$
0
votes
\$\begingroup\$

C++

I'm aware there have been a couple of similarly themed solutions, but here's mine nonetheless:

#include <iostream>

struct Plus {
  int x;
  Plus(int _x):x(_x){}
  Plus operator+(int _x) {
    return Plus(this->x + _x);
  }
  bool operator==(Plus _x) {
    return true;
  }
};

int main() {
  Plus x(0);
  std::cout << bool(x == x + 2); 
}
\$\endgroup\$
0
votes
\$\begingroup\$

Python

I'm always looking for an excuse to use a class for golfing Python... alas, this isn't golf.

class foo:__add__=lambda a,b:a
x=foo()

Here, x+2 is x, though 2+x blows up with an error (I'd have to implement __radd__). I could have hacked equality testing instead, but I'd still need to implement __add__.

\$\endgroup\$
  • \$\begingroup\$ class foo(int):__cmp__=lambda*a:0 is easier \$\endgroup\$ – gnibbler Sep 11 '12 at 20:11
  • \$\begingroup\$ @gnibbler, I'd agree if addition didn't raise an exception. \$\endgroup\$ – boothby Sep 13 '12 at 4:48
  • \$\begingroup\$ Which version of Python are you using? It doesn't raise an exception on 2.7.3 \$\endgroup\$ – gnibbler Sep 13 '12 at 6:21
  • \$\begingroup\$ @gnibbler, ooh, I missed the (int). sneaky sneaky. don't know that I'd call it 'easier'. \$\endgroup\$ – boothby Sep 14 '12 at 5:26
  • \$\begingroup\$ well it's easier because you get to support 2+x for free \$\endgroup\$ – gnibbler Sep 14 '12 at 5:43
0
votes
\$\begingroup\$

Python

Any language with floats - no need to go all the way to infinity

x=9e9**9
x==x+2
\$\endgroup\$
0
votes
\$\begingroup\$

q/k

Pretty trivial using infinity (or null):

q)x:0w

x=x+2
1b
\$\endgroup\$
0
votes
\$\begingroup\$

Processing

float x=1e30;
print(x==x+2);

The output will be true

Not very creative, but yeah.

\$\endgroup\$
0
votes
\$\begingroup\$

Python

class X():
 def __eq__(a,b):
  return True
 def __add__(a,b):
  return True
x = X()
print x==x+2
$ python x.py 
True
\$\endgroup\$
0
votes
\$\begingroup\$

Sage

sage: print oo
+Infinity
sage: oo+2==oo
True
\$\endgroup\$
0
votes
\$\begingroup\$

Groovy

Integer.metaClass.plus = { Integer y -> delegate }
def x = 0
assert x == x+2

The plus method is overridden to return the first number :-D

\$\endgroup\$
0
votes
\$\begingroup\$

C (GCC at least)

Using pointer arithmetic on an struct of size 0

#include <stdio.h>
typedef struct {} empty;

main(){
    empty *x;
    printf("%d\n", x==x+2);
}
\$\endgroup\$
0
votes
\$\begingroup\$

Coffeescript, 18 chars

x=1/0;alert x==x+2
\$\endgroup\$
0
votes
\$\begingroup\$

Lua, used in various products including World of Warcraft, Wireshark, Nmap, Adobe Photoshop Lightroom, and the Nspire line of Texas Instruments graphing calculators, supports operator overloading (using "metamethods") for tables (associative arrays). This code works in both Lua 5.1 and 5.2:

local x = setmetatable({}, {
  __add = function(a, b)
    return a
  end
})

print(x == x + 2) -- true
\$\endgroup\$
0
votes
\$\begingroup\$

GolfScript

In Golfscript, you can redefine +, 2, or = in order to make the statement true for any value of x! Any of the following lines would suffice:

{;}:+; #Redefine + to ignore the second summand
0:2;; #Redefine 2 to be 0
{;;1}:=; #Redine = to always return true

Then:

10:x; #Any x would work
x x 2+ = #x==x+2
-> 1

If you want the answer in the exactly format of the question, we can do some other nonsense:

{0}:(:x:=:+:2; #redefine all the characters in the expression to 0
{];1}:); #redefine ) to pop everything off the stack and then return 1

So then:

(x == x+2)  #That doesn't look like GolfScript!
-> 1
\$\endgroup\$
0
votes
\$\begingroup\$

Little know fact about Haskell is it doesn't always do divide by 0 errors.

let x=1/0 in x==x+2

This is because when you add 2 to infinity, it doesn't get bigger. It is weird that such a mathematical language would just deal with infinity so nonchalantly.

\$\endgroup\$
0
votes
\$\begingroup\$

Rebol

Version of the Perl answer by memowe:

v: 0
x: does [v: v - 2]

With above defined you can now test in Rebol console...

>> x == (x + 2)
== true

>> equal? x x + 2
== true

And a Rebol version of Joshua Taylor Common Lisp answer:

x: 42
x+2: 42

In console...

>> x == x+2  
== true
\$\endgroup\$
0
votes
\$\begingroup\$

Groovy

x = Float.MAX_VALUE
assert x==x+2


Float.MAX_VALUE = 3.4028235E38
Float.MAX_VALUE + 2 = 3.4028234663852886E38
Which the == determines is close enough.

\$\endgroup\$
0
votes
\$\begingroup\$

C++ / C-sharp

Here's another one depending on the definition of an infinite double according to the IEEE standard (http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlf101a.doc%2Fxlfopg%2Ffpieee.htm).

int main()
{
   double x = 0x7FF0000000000000; // Positive infinity
   cout << (x == x + 2 ? "true" : "false");

   return 0;
}

In C# this could be written more readably as

 double x = double.PositiveInfinity;
\$\endgroup\$
0
votes
\$\begingroup\$

C++

Had some fun with operator overloading

#include <iostream>

class Tautology
{
  public:
    const Tautology& operator+(int n)
    {
        // Anything to make x + 2 compile
        return *this;
    }

    bool operator==(const Tautology& t)
    {
        // Any tautology equals any other
        return true;
    }
};

int main()
{
   Tautology x;
   std::cout << (x == x + 2 ? "true" : "false");

   return 0;
}
\$\endgroup\$
0
votes
\$\begingroup\$

JavaScript

Exploiting the big number / infinity approach as shortly as possible.

12 chars:

9e99==9e99+2 // true

10 chars

1/0==1/0+2 // true
\$\endgroup\$
0
votes
\$\begingroup\$

Python

>>> x=99999999999999999999999999999999999.
>>> x==x+2
True

Note the . at the end, which makes x a floating point number.

\$\endgroup\$
0
votes
\$\begingroup\$

Python (18)

>>> x=True;[x][x==2+x]
True

Gives True in interactive mode.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.