Take the 2-minute tour ×
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
    
Why the explicit hate for the preprocessor? It's a legitimate part of the language, and in C's case, of the culture. –  J B Sep 7 '12 at 11:45
21  
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
2  
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. –  user unknown Dec 19 '12 at 21:20

91 Answers 91

up vote 56 down vote accepted
main()
{
double x=1.0/0.0;
printf("%d",x==x+2);
}

Outputs 1.

Link: http://ideone.com/dL6A5

share|improve this answer
7  
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
1  
Ahh good old divide by zero. That took me longer to figure out than I'd like to admit. haha –  Grant Sep 7 '12 at 7:11
    
Argh, I also though of this, but on Windows is doesn't compile so I dropped it. :( +1 though –  Tudor Sep 7 '12 at 10:09
    
x=1e999 is another way of doing this. –  shiona Sep 8 '12 at 15:36
2  
@shiona float x=1e20 would be enough –  l0n3sh4rk Sep 8 '12 at 16:42

Fortran IV:

2=0

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

share|improve this answer
9  
All the more reason for me to never touch Fortran. –  C0deH4cker Jan 24 at 19:35
2  
Does it at least throw a warning? –  Michael Stern Mar 10 at 16:24
6  
@MichaelStern WARNING: YOU ARE CHANGING THE VALUE OF 2! –  Cruncher Mar 10 at 20:19

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.

share|improve this answer
2  
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
    
Is it just me or should 2|(0+2) be 1? –  phunehehe Sep 9 '12 at 15:50
1  
@phunehehe: | is bitwise OR; || is logical OR. –  PleaseStand Sep 9 '12 at 16:38
7  
This somehow reminds me of little Bobby Tables. –  vsz Oct 5 '12 at 21:14
1  
@rakeshNS: I added the extra set of parentheses to show operator precedence. That's why I said "Basically". –  PleaseStand Apr 9 '13 at 23:05

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.

share|improve this answer
3  
+1 Must be the most creative bending of the rules. –  ninjalj Nov 18 '12 at 0:48
3  
Why do you need the x? –  James Apr 3 '13 at 22:11
    
@James The question says to define x so here x is defined as x. –  user80551 Mar 11 at 2:48

F#

let (==) _ _ = true
let x = 0
x == (x + 2) //true
share|improve this answer
6  
I like this one. Instead of juggling numbers, simply redefine the meaning of == –  evilcandybag Sep 6 '12 at 22:17
3  
Hang on, isn't the equality operator in F# simply =? == isn't even defined by default. –  Jwosty Mar 11 at 13:16

C

int main() { float x = 1e10; printf("%d\n", x == x + 2); }
share|improve this answer
10  
+1 for real-world applications. Too many people don't understand floating point mathematics. –  Tim S. Mar 10 at 14:16

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.

share|improve this answer
3  
You can simplify: fromInteger = odd –  Rotsor Sep 8 '12 at 2:54
1  
Also (+) can be defined as (/=) I believe. –  MatrixFrog Dec 18 '12 at 8:25
1  
Shorter solution would be to make an instance for (). –  Thomas Eding Jun 11 '13 at 17:26

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

share|improve this answer
1  
Dang it, just got a 'Nice Answer' badge for this post. Seriously, getting badges for EVIL stuff?! Don't do this at home! –  fjdumont Apr 19 '13 at 9:22
    
It's evil, but it's so beautiful... –  Kevin Mar 10 at 20:17

Python

class X(int):__add__=lambda*y:0
x=X()

# Then (x == x+2) == True
share|improve this answer
    
Nice. All languages which support operator overloading can use similar solutions, but C isn't one of them. –  ugoren Sep 6 '12 at 10:05
    
Also works with overloading __cmp__ as class X(int):__cmp__=lambda*x:0 (or __eq__ though slightly longer class X(int):__eq__=lambda*x:True –  dr jimbob Sep 6 '12 at 17:21
    
A couple characters shorter if you dont extend from int.. class X:__add__=lambda s,o:s –  Doboy Sep 15 '12 at 4:55
    
May I ask what that multiplication does? –  Sieg Jun 5 at 15:25
    
@TheRare it's not actually multiplication. Because __add__ is normally given multiple arguments (lambda x,y:), I save some characters by using * to pack all the arguments into a tuple (lambda *y:). See the docs for more info. –  grc Jun 6 at 0:05

GNU C supports structures with no members and size 0:

struct {} *x = 0;
share|improve this answer
    
Very nice! I thought about pointer arithmetic with very large data leading to wraparound, but didn't think of the opposite. –  ugoren Sep 7 '12 at 15:13

PHP:

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

Or:

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

Output:

bool(true)

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

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_IMPL(c, d) (c ## d)
#define CAT(c, d) CAT_IMPL(c, d)
#define x CAT(a, __LINE__)

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

Prints 1.

share|improve this answer
    
+1 for a very inventive use of the preprocessor. –  Ken Bloom Sep 6 '12 at 23:35
    
Nice, though perhaps not technically valid (x == x+2 is still false). But once you bring up the idea, I think #define x -2*__LINE__ is more elegant. –  ugoren Sep 7 '12 at 8:10
3  
@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
    
_CAT is reserved identifier. Anything that starts with underscore, and uppercase letter is reserved in C. –  xfix Feb 21 at 7:13
    
@xfix that's exactly right, updated to remove UB. –  H2CO3 Feb 22 at 22:47

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!

share|improve this answer
1  
0. Nope, still don't believe it. –  MSalters Sep 7 '12 at 11:59
    
@MSalters: What compiler do you use? You might have trigraphs disabled. –  vsz Sep 7 '12 at 21:31
    
VS2010. Quite possible that trigraphs are disabled by default. Either that or line concatenation doesn't work with ??\ –  MSalters Sep 10 '12 at 9:44
    
MSalters: the trigraph ??\ is to be converted into a single \ , so there is no ??\ . Some modern compilers however give warnings by default to both trigraphs and line concatenations even if enabled. –  vsz Sep 10 '12 at 19:58

Javascript:

var x = 99999999999999999;
alert(x == x+2);​

Test Fiddle

share|improve this answer
2  
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
6  
@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
    
This is the only real-world case in which I saw a check like this for a good reason (besides programming riddles): A (float-based) faculty-function was checking its input for being too great to be counted down by -1 and recursing. The language itself was Python, but that does not really matter in this case. –  Alfe Sep 7 '12 at 12:19
4  
@NicoBurns not ture :( –  ajax333221 Sep 8 '12 at 22:27
2  
@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

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.

share|improve this answer
1  
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
    
Thank you @ugoren, I spend most of my time on the Mathematica Stack Exchange website, so I forgot to explain what made my example meaningful. I made an edit that explains the concept as concisely I could. –  Carl Morris Sep 7 '12 at 17:41

scheme

(define == =)
(define (x a b c d) #t)
(x == x + 2)
;=> #t
share|improve this answer
    
Nice. Scheme's (x == x + 2) looks just like C's, but means a totally different thing. –  ugoren Sep 7 '12 at 15:07
1  
Now do it for (= x 2). –  Joe Z. Aug 15 '13 at 16:40

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

int (*x)[0x2000000000000000];
share|improve this answer
    
Great in principle, but seems to be implemented wrong. x would be incremented in steps of 2^61, so x + 8 would equal x. –  ugoren Sep 7 '12 at 15:12
    
@ugoren, it works for me, on Linux with 4-byte int. –  han Sep 7 '12 at 16:07
    
You're absolutely right. I missed the fact that it's an array of int, not char. –  ugoren Sep 7 '12 at 20:25

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);
share|improve this answer
    
A nice concept - making x be a function call, although it looks like a variable read. I assumes left-to-right evaluation order, but it's OK since it's specified in JS (unlike C). –  ugoren Sep 6 '12 at 12:21
    
+1 for the awesomeness –  BernaMariano Dec 18 '12 at 0:11

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.

share|improve this answer

Obvious answer:

When this terminates:

while (x != x+2) { }
printf("Now");
share|improve this answer
    
+1 meta.codegolf.stackexchange.com/a/1070/8766 but this is actually ingenious. –  user80551 Mar 10 at 14:06

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

share|improve this answer
1  
Same trick works with PARI/GP –  Hagen von Eitzen Sep 6 '12 at 17:18

Perl

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

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

Output: true!

share|improve this answer
1  
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
2  
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 '13 at 1:00
    
That's awesome, @mykhal and @Perleone! –  memowe Jan 20 '13 at 14:07

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.

share|improve this answer
    
I really like this because it's the first answer to exploit float precision. –  AndrewKS Sep 6 '12 at 16:31
1  
@AndrewKS: Actually Paul R was a bit earlier. –  MSalters Sep 7 '12 at 11:48

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.

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

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;
}
share|improve this answer
    
You can use std::boolalpha instead of ?:. –  Jon Purdy Sep 6 '12 at 17:58

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

If it is ok to exploit the question a little bit, then I will add some new Java. The trick is for sure not new, but perhaps interesting that this is possible in Java.

static void pleaseDoNotDoThis() throws Exception {
    Field field = Boolean.class.getField("FALSE");
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, true);
}

public static void main(String args[]) throws Exception {
    pleaseDoNotDoThis();
    doit(1);
    doit("NO");
    doit(null);
    doit(Math.PI);
}

static void doit(long x) {
    System.out.format("(x == x + 2) = (%d == %d) = %s\n", x, x+2, (x == x + 2));
}

static void doit(String x) {
    System.out.format("(x == x + 2) = (%s == %s) = %s\n", x, x+2, (x == x + 2));
}

static void doit(double x) {
    System.out.format("(x == x + 2) = (%f == %f) = %s\n", x, x+2, (x == x + 2));
}

And the results:

(x == x + 2) = (1 == 3) = true
(x == x + 2) = (NO == NO2) = true
(x == x + 2) = (null == null2) = true
(x == x + 2) = (3,141593 == 5,141593) = true
(x == x + 2) = (Infinity == Infinity) = true
share|improve this answer

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

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
share|improve this answer
    
I was going to post the very same solution in ruby, until I saw yours - it's possible because both languages permit omission of the parentheses. –  waldrumpus Sep 6 '12 at 12:27

protected by Community Mar 10 at 16:29

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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