Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
14  
Why 4. Quick? You mean "Whoever knows one and is lucky enough to read this question first"? – Luc Sep 7 '12 at 21:43
5  
@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
2  
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

71 Answers

Ruby

def x;1.0/0;end
puts (x == x+2) #=> true
share|improve this answer

JavaScript

Here's a way do it without exploiting Infinity:

x = {
    value: 0,
    valueOf: function () {
        this.value += 2;
        return this.value;
    }
};

alert(x == x+2);
share|improve this answer

Perl 6

I'm surprised to not see this solution before. Anyway, the solution is - what if x is 0 and 2 at once? my \x in this example declares sigilless variable - this question asks about x, not Perl-style $x. The ?? !! is ternary operator.

$ perl6 -e 'my \x = 0|2; say x == x + 2 ?? "YES" !! "NO"'
YES

But...

$ perl6 -e 'my \x = 0|2; say x == x + 3 ?? "YES" !! "NO"'
NO

x is multiple values at once. x is equal to 0 and 2 at once. x + 2 is equal to 2 and 4 at once. So, logically they're equal.

share|improve this answer

Python 2.X (Using redefinition of (cached) integers)

I've noticed all of the python answers have defined classes that redefine the + operator. I'll answer with an even more low-level demonstration of python's flexibility. (This is a python2-specific snippet)

In python, integers are stored more or less this way in C:

typedef struct {            // NOTE: Macros have been expanded
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
    long ob_ival;
} PyIntObject;

That is, a struct with a size_t, void *, and long object, in that order.
Once we use, and therefore cache an integer, we can use python's ctypes module to redefine that integer, so that not only does x == x+2, but 2 == 0

import ctypes
two = 2 # This will help us access the address of "2" so that we may change the value

# Recall that the object value is the third variable in the struct. Therefore,
# to change the value, we must offset the address we use by the "sizeof" a 
# size_t and a void pointer
offset = ctypes.sizeof(ctypes.c_size_t) + ctypes.sizeof(ctypes.c_voidp)

# Now we access the ob_ival by creating a C-int from the address of 
# our "two" variable, offset by our offset value.
# Note that id(variable) returns the address of the variable.
ob_ival = ctypes.c_int.from_address(id(two)+offset)

#Now we change the value at that address by changing the value of our int.
ob_ival.value = 0

# Now for the output
x = 1
print x == x+2
print 2 == 0

Prints

True
True
share|improve this answer

GAP

gap> x:=[];
[  ]
gap> x=x+2;
true

Here x is an empty array.

gap> x:=Z(2);
Z(2)^0
gap> x=x+2;
true

Here x is a generator of GF(2).

gap> x:=Integers;
Integers
gap> x=x+2;
true

Here x is the set of integers.

share|improve this answer

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

share|improve this answer
show 1 more comment

C#

Using infinity

Double x = Double.PositiveInfinity;
Console.WriteLine(String.Format("Result: {0}", x == x + 2));

Also works with

Double x = Double.NegativeInfinity

(this is actually the same as 1.0 / 0.0 approach)

share|improve this answer

C#

I didn't see any rule stating x had to be a number:

class Program {
    public static Program operator +(Program x, int y) {
        return x;
    }

    static void Main(string[] args) {
        var x = new Program();
        Console.WriteLine(x == x + 2);
    }
}

I defined x in such a way, but I also defined the + operator for the object stored in x.

http://ideone.com/ylNyM

share|improve this answer

If you evaluate (x==x+2) directly you will get a false, but I think it is interesting because it makes usage of a different language feature.

#include <stdio.h>

typedef struct {
  int bit:1;
} bitpack;

#define x a.bit
#define y b.bit

main() 
{
  bitpack a, b;
  y = x + 2;
  if (x==y) 
    printf("true\n");
  else 
    printf("false\n");
}
share|improve this answer

Python:

>>> x=float('inf')
>>> x==x+2
True
share|improve this answer

Java:

Float x = Float.MAX_VALUE;
System.out.println(x == (x + 2));

It prints "true"

System.out.println(x); 

prints 3.4028235E38

System.out.println(x+2); 

prints 3.4028235E38

I think this is caused by the loss of precision.

share|improve this answer

In my opinion, x must have a data type of just ONE BIT.

Since C99, there is the data type _Bool ; So this should probably work:

_Bool x;
x = 0;
if (x == x + 2) ...
share|improve this answer

C

let the computer find a value for x

int main()
{
  float x=0;
  while(x!=x+2)x+=2;
  printf("%f\n",x);
}
share|improve this answer

Haskell

Prelude> instance Num Bool where (+) _ _ = True
Prelude> let x = True
Prelude> (x==x+2)
True

You could call that cheating but I assume that's what this is about :D

To make it work with more than just bool:

import Prelude hiding ((==),(+))
infixl 9 ==
(==) _ _ = True
(+) _ _ = True
share|improve this answer

Pascal

Here's a solution that takes a different approach (not the usual infinity trick).

Program xplus2;

Var value: integer;

Function x: integer;
Begin
   value := value-2;
   x := value;
End;

Begin
   If x=x+2 then
      Writeln('They are the same')
   else
      WriteLn('They are different');
End.

Works with 2+x too.

share|improve this answer
show 1 more comment

Missing GolfScript?

0:2;
Then e.g. 15 2+ -> 15

share|improve this answer
show 2 more comments
 cout << bool(x == x+2);

! is not needed at all

share|improve this answer
1  
It depends on the initialization of x, which isn't shown. So, no points for this answer. – MSalters Sep 7 '12 at 11:51
show 8 more comments

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 
share|improve this answer

Scala

case object x {
  def +(n:Int) = this
}
//defined module x

x == x + 2
//res0: Boolean = true
share|improve this answer

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> 
share|improve this answer

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);

M 

Mo 

Mor

More 

More.

More..
share|improve this answer

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 => [ ]

share|improve this answer

PYTHON:

x=9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.

x

1e+103

x+2

1e+103

share|improve this answer

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.

share|improve this answer

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); 
}
share|improve this answer

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__.

share|improve this answer
show 6 more comments

Python

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

x=9e9**9
x==x+2
share|improve this answer

q/k

Pretty trivial using infinity (or null):

q)x:0w

x=x+2
1b
share|improve this answer

Processing

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

The output will be true

Not very creative, but yeah.

share|improve this answer

Haskell

f x = x == (x+2) where (==)=(<)

Always returns True, except when x is 1/0.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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