# When does (x == x+2)?

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.

Winning criteria:
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.

-
Why 4. Quick? You mean "Whoever knows one and is lucky enough to read this question first"? – Luc Sep 7 '12 at 21:43
@ugoren Let the community vote (and vote yourself for ones you like), then choose the top answer after 7 days or so :) – Luc Sep 8 '12 at 21:48
Regarding possibility 2: NaN doesn't work. NaN+2 is again NaN, but NaN==NaN is false. – Martin B Oct 26 '12 at 13:51
show 10 more comments

main() { double x=1.0/0.0; printf("%d",x==x+2); }

Outputs 1.

-
float x=1./0 is a bit shorter and perhaps more elegant. But anyway, this surely is the first good answer. – ugoren Sep 6 '12 at 10:37
show 4 more comments

This seems to work:

#define x 2|0

Basically, the expression is expanded to (2|0 == 2|(0+2)). It is a good example of why one should use parentheses when defining macros.

-
Certainly works, and I think it's the most elegant preprocessor based solution. But I think doing it without the preprocesor is more interesting. – ugoren Sep 6 '12 at 10:04
This somehow reminds me of little Bobby Tables. – vsz Oct 5 '12 at 21:14
show 5 more comments

Fortran IV:

2=0

After this every constant 2 in the program is zero. Trust me, I have done this (ok, 25 years ago)

-

## Brainfuck

x

This does of course stretch "evaluate to true" a bit, because in Brainfuck nothing actually evaluates to anything – you only manipulate a tape. But if you now append your expression

x
(x == x+2)

the program is equivalent to

+

(because everything but <>+-[],. is a comment). Which does nothing but increment the value where we are now. The tape is initialised with all zeros, so we end up with a 1 on the cursor position, which means "true": if we now started a conditional section with [], it would enter/loop.

-
+1 Must be the most creative bending of the rules. – ninjalj Nov 18 '12 at 0:48
Why do you need the x? – James Apr 3 at 22:11

# F#

let (==) _ _ = true
let x = 0
x == (x + 2) //true
-
I like this one. Instead of juggling numbers, simply redefine the meaning of == – evilcandybag Sep 6 '12 at 22:17

## Python

x=X()

# Then (x == x+2) == True
-
show 3 more comments

## C

int main() { float x = 1e10; printf("%d\n", x == x + 2); }
-

Scala: { val x = Set(2); (x == x + 2) }

Haskell: Define ℤ/2ℤ on Booleans:

instance Num Bool where
(+) = (/=)
(-) = (+)
(*) = (&&)
negate = id
abs    = id
signum = id
fromInteger = odd

then for any x :: Bool we'll have x == x + 2.

Update: Thanks for the ideas in comment, I updated the instance accordingly.

-
You can simplify: fromInteger = odd – Rotsor Sep 8 '12 at 2:54
Also (+) can be defined as (/=) I believe. – MatrixFrog Dec 18 '12 at 8:25

PHP:

\$x = true;
var_dump(\$x == \$x+2);

Or:

var_dump(!(\$x==\$x+2));

Output:

bool(true)

-
I was actually trying to come up with this dead-simple PHP answer, but you beat me to it. – PleaseStand Sep 6 '12 at 12:54

GNU C supports structures with no members and size 0:

struct {} *x = 0;
-
show 1 more comment

It's a common misconception that in C, whitespace doesn't matter. I can't imagine somebody hasn't come up with this in GNU C:

#include <stdio.h>
#define _CAT(c, d) (c ## d)
#define CAT(c, d) _CAT(c, d)
#define x CAT(a, __LINE__)

int main()
{
int a9 = 2, a10 = 0;
printf("%d\n", x ==
x + 2);
return 0;
}

Prints 1.

-
@ugoren thanks! If you want all this to be on one line, use COUNTER instead of LINE - requires GCC 4.3+ though. – H2CO3 Sep 7 '12 at 9:58
show 2 more comments

C#

class T {
static int _x;
static int X { get { return _x -= 2; } }

static void Main() { Console.WriteLine(X == X + 2); }
}

Not a shortie, but somewhat elegant.

http://ideone.com/x56Ul

-
show 1 more comment

C

It's more interesting without using macros and without abusing infinity.

/////////////////////////////////////
// At the beginning                 /
// We assume truth!                 /

int truth = 1;
int x = 42;

/////////////////////////////////////
// Can the truth really be changed??/
truth = (x == x + 2);

/////////////////////////////////////
// The truth cannot be changed!     /
printf("%d",truth);

Try it if you don't believe it!

-
0. Nope, still don't believe it. – MSalters Sep 7 '12 at 11:59
show 3 more comments

Javascript:

var x = 99999999999999999;

Test Fiddle

-
You could use Infinity, or -Infinity, and because of this you could use the shortcut of x = 1/0. – zzzzBov Sep 6 '12 at 15:36
@zzzzBov: That's definitely a better code golf. I chose (99999999999999999 == 99999999999999999+2) because I think it's a bit more interesting than (Infinity == Infinity+2), though as the OP says, "it's subjective" :) – Briguy37 Sep 6 '12 at 15:49
@NicoBurns not ture :( – ajax333221 Sep 8 '12 at 22:27
@NicoBurns, running that code in the console produces false; wherever you're getting that info on JS is wrong and should not be trusted. – zzzzBov Sep 8 '12 at 23:09
show 3 more comments

The following is not standards compliant C, but should work on just about any 64-bit platform:

int (*x)[0x2000000000000000];
-
show 3 more comments

Sage:

x=Mod(0,2)
x==x+2

returns True

In general for GF(2**n) it's always true that x=x+2 for any x

This is not a bug or an issue with overflow or infinity, it's actually correct

-
Same trick works with PARI/GP – Hagen von Eitzen Sep 6 '12 at 17:18

Mathematica:

x /: x + 2 := x
x == x + 2

I think this solution is novel because it uses Mathematica's concept of Up Values.

EDIT:

I am expanding my answer to explain what Up Values mean in Mathematica.

The first line essentially redefines addition for the symbol x. I could directly store such a definition in the global function that is associated with the + symbol, but such a redefinition would be hazardous because the redefinition may propagate unpredictably through Mathematica's built-in algorithms.

Instead, using the tag x/:, I associated the definition with the symbol x. Now whenever Mathematica sees the symbol x, it checks to see whether it is being operated on by the addition operator + in a pattern of the form x + 2 + ___ where the symbol ___ means a possible null sequence of other symbols.

This redefinition is very specific and utilizes Mathematica's extensive pattern matching capabilities. For example, the expression x+y+2 returns x+y, but the expression x+3 returns x+3; because in the former case, the pattern could be matched, but in the latter case, the pattern could not be matched without additional simplification.

-
I think you should explain what it does. Most people don't know Mathematica (or what Up Values are). – ugoren Sep 7 '12 at 8:08
show 1 more comment

Here is a solution for JavaScript that does not exploit the Infinity and -Infinity edge cases of floating-point addition. This works neither in Internet Explorer 8 and below nor in the opt-in ES5 strict mode. I would not call the with statement and getters particularly "advanced" features.

with ({ \$: 0, get x() {return 2 * this.\$--;} }) {
console.log(x == x+2);
}

Edited to add: The above trick is also possible without using with and get, as noted by Andy E in Tips for golfing in JavaScript and also by jncraton on this page:

var x = { \$: 0, valueOf: function(){return 2 * x.\$++;} };
console.log(x == x+2);
-
show 2 more comments

## scheme

(define == =)
(define (x a b c d) #t)
(x == x + 2)
;=> #t
-
show 1 more comment

## Common Lisp

* (defmacro x (&rest r) t)
X
* (x == x+2)
T

It's pretty easy when x doesn't have to be an actual value.

-

## Perl

using a subroutine with side-effects on a package variable:

sub x () { \$v -= 2 }
print "true!\n" if x == x + 2;

Output: true!

-
sub x{} "works" as well.. (at least in my 5.10.1), but i can't figure why.. – mykhal Dec 16 '12 at 8:27
Because sub x{} returns either undef or an empty list, both of which are a numeric zero. And x + 2 is parsed as x(+2). perl -MO=Deparse reveals print "true\n" if x() == x(2); – Perleone Jan 20 at 1:00
show 1 more comment

## APL (Dyalog)

X←1e15
X=X+2

APL does not even have infinity, it's just that the floats aren't precise enough to tell the difference between 1.000.000.000.000.000 and 1.000.000.000.000.002. This is, as far as I know, the only way to do this in APL.

-
show 2 more comments

Python

exploiting floating point precision makes this very simple.

>>> x = 100000000000000000.0
>>> (x == x+2)
True

To make it less system specific requires an extra import

>>> import sys
>>> x = float(sys.maxint + 1)
>>> (x == x+2)
True

This should work in other languages too. This works because the reprensentation of 100000000000000000.0 and 100000000000000002.0 are exactly the same for the machine, because of the way floating points are represented inside the machine. see http://en.wikipedia.org/wiki/IEEE_floating_point for more information.

So this will basically work in any language that allows you to add integers to floats and have the result of this be a float.

-

I know it's a code challenge... but I golfed it. Sorry.

Ruby - 13 characters - Infinity solution

x=1e17;x==x+2

returns true

Ruby - 41 characters - Op Overloading solutions

class Fixnum;def + y;0 end end;x=0;x==x+2

or

class A;def self.+ y;A end end;x=A;x==x+2
-

Here is a solution for C++ based on operator overloading. It relies on implicit conversion from an enum to an int.

#include <iostream>

enum X {};
bool operator==(X x, int y)
{
return true;
}

int main()
{
X x;
std::cout << std::boolalpha << (x == x+2) << std::endl;
return 0;
}
-
show 1 more comment

# When this terminates:

while (x != x+2) { }
printf("Now");
-

procedure test() is
type x_type is mod 2;
var x: x_type := 0; -- 0 or 1
begin
if x /= x + 2 then
put('Error');
else
put('Equal!');
end if;
end test;

This is similar to Sage. We use a 1 bit integer which is allowed to wrap. We could also use a floating point, obviously.

-

## PHP

<?php
\$x = 1e17;
echo \$x==\$x+2;

Works in many other languages as well.

-

This VBScript solution works similarly to my JavaScript solution. I did not use a preprocessor yet the solution seems trivial.

y = 0
Function x
x = y
y = -2
End Function

If x = x + 2 Then
WScript.Echo "True"
Else
WScript.Echo "False"
End If
-
show 1 more comment

Ruby

def x;1.0/0;end
puts (x == x+2) #=> true
-