89
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\$
17
  • 29
    \$\begingroup\$ Why 4. Quick? You mean "Whoever knows one and is lucky enough to read this question first"? \$\endgroup\$
    – Luc
    Commented Sep 7, 2012 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
    Commented Sep 8, 2012 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
    Commented Oct 26, 2012 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\$ Commented Dec 19, 2012 at 21:20
  • 2
    \$\begingroup\$ Why are this question and all the answers Community Wiki? \$\endgroup\$
    – mbomb007
    Commented Jul 2, 2015 at 18:49

98 Answers 98

124
votes
\$\begingroup\$

Fortran IV:

2=0

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

\$\endgroup\$
3
  • 23
    \$\begingroup\$ All the more reason for me to never touch Fortran. \$\endgroup\$
    – C0deH4cker
    Commented Jan 24, 2014 at 19:35
  • 3
    \$\begingroup\$ Does it at least throw a warning? \$\endgroup\$ Commented Mar 10, 2014 at 16:24
  • 15
    \$\begingroup\$ @MichaelStern WARNING: YOU ARE CHANGING THE VALUE OF 2! \$\endgroup\$
    – Cruncher
    Commented Mar 10, 2014 at 20:19
99
votes
\$\begingroup\$

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.

\$\endgroup\$
7
  • 3
    \$\begingroup\$ Certainly works, and I think it's the most elegant preprocessor based solution. But I think doing it without the preprocesor is more interesting. \$\endgroup\$
    – ugoren
    Commented Sep 6, 2012 at 10:04
  • \$\begingroup\$ Is it just me or should 2|(0+2) be 1? \$\endgroup\$
    – phunehehe
    Commented Sep 9, 2012 at 15:50
  • 1
    \$\begingroup\$ @phunehehe: | is bitwise OR; || is logical OR. \$\endgroup\$ Commented Sep 9, 2012 at 16:38
  • 20
    \$\begingroup\$ This somehow reminds me of little Bobby Tables. \$\endgroup\$
    – vsz
    Commented Oct 5, 2012 at 21:14
  • 1
    \$\begingroup\$ @rakeshNS: I added the extra set of parentheses to show operator precedence. That's why I said "Basically". \$\endgroup\$ Commented Apr 9, 2013 at 23:05
78
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 12
    \$\begingroup\$ +1 Must be the most creative bending of the rules. \$\endgroup\$
    – ninjalj
    Commented Nov 18, 2012 at 0:48
  • 3
    \$\begingroup\$ Why do you need the x? \$\endgroup\$
    – James
    Commented Apr 3, 2013 at 22:11
  • 3
    \$\begingroup\$ @James The question says to define x so here x is defined as x. \$\endgroup\$
    – user80551
    Commented Mar 11, 2014 at 2:48
  • 1
    \$\begingroup\$ @James the answer doesn't need anything except the + \$\endgroup\$
    – Cruncher
    Commented Sep 30, 2014 at 15:07
71
votes
\$\begingroup\$
main()
{
double x=1.0/0.0;
printf("%d",x==x+2);
}

Outputs 1.

Link: http://ideone.com/dL6A5

\$\endgroup\$
5
  • 7
    \$\begingroup\$ float x=1./0 is a bit shorter and perhaps more elegant. But anyway, this surely is the first good answer. \$\endgroup\$
    – ugoren
    Commented Sep 6, 2012 at 10:37
  • 1
    \$\begingroup\$ Ahh good old divide by zero. That took me longer to figure out than I'd like to admit. haha \$\endgroup\$
    – Grant
    Commented Sep 7, 2012 at 7:11
  • \$\begingroup\$ Argh, I also though of this, but on Windows is doesn't compile so I dropped it. :( +1 though \$\endgroup\$
    – Tudor
    Commented Sep 7, 2012 at 10:09
  • \$\begingroup\$ x=1e999 is another way of doing this. \$\endgroup\$
    – shiona
    Commented Sep 8, 2012 at 15:36
  • 4
    \$\begingroup\$ @shiona float x=1e20 would be enough \$\endgroup\$
    – l0n3sh4rk
    Commented Sep 8, 2012 at 16:42
55
votes
\$\begingroup\$

F#

let (==) _ _ = true
let x = 0
x == (x + 2) //true
\$\endgroup\$
2
  • 13
    \$\begingroup\$ I like this one. Instead of juggling numbers, simply redefine the meaning of == \$\endgroup\$ Commented Sep 6, 2012 at 22:17
  • 4
    \$\begingroup\$ Hang on, isn't the equality operator in F# simply =? == isn't even defined by default. \$\endgroup\$
    – Jwosty
    Commented Mar 11, 2014 at 13:16
50
votes
\$\begingroup\$

C

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

Note: may not work if FLT_EVAL_METHOD != 0 (see comments below).

\$\endgroup\$
9
  • 24
    \$\begingroup\$ +1 for real-world applications. Too many people don't understand floating point mathematics. \$\endgroup\$
    – Tim S.
    Commented Mar 10, 2014 at 14:16
  • 1
    \$\begingroup\$ @mbomb007: I think they are different - the answer you link to relies on INF + 2 == INF, whereas my answer uses a single precision float which is large enough that 2 is less than one ULP. \$\endgroup\$
    – Paul R
    Commented Nov 30, 2016 at 14:55
  • 2
    \$\begingroup\$ @mbomb007: I also think they're very different - ∞ + 2 = ∞ is something anyone could understand and doesn't depend on anything computer specific, whereas adding 2 to a concrete number and it having no effect is a bit more surprising and specific to the limited precision of computers, and more interesting IMHO \$\endgroup\$ Commented Nov 30, 2016 at 15:20
  • 1
    \$\begingroup\$ This can readily fail when FLT_EVAL_METHOD == 1 as the math is done as double. Recommend a larger FP value sure to exceed even long double precision like 1.0e37f \$\endgroup\$
    – chux
    Commented May 3, 2017 at 18:21
  • 1
    \$\begingroup\$ @chux: thanks for the confirmation - that's definitely something I may need to watch out for in future, as much of my code ends up being cross-platform. \$\endgroup\$
    – Paul R
    Commented May 3, 2017 at 18:40
36
votes
\$\begingroup\$

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

\$\endgroup\$
2
  • 4
    \$\begingroup\$ Dang it, just got a 'Nice Answer' badge for this post. Seriously, getting badges for EVIL stuff?! Don't do this at home! \$\endgroup\$
    – fjdumont
    Commented Apr 19, 2013 at 9:22
  • \$\begingroup\$ It's evil, but it's so beautiful... \$\endgroup\$
    – Kevin
    Commented Mar 10, 2014 at 20:17
32
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • 3
    \$\begingroup\$ You can simplify: fromInteger = odd \$\endgroup\$
    – Rotsor
    Commented Sep 8, 2012 at 2:54
  • 1
    \$\begingroup\$ Also (+) can be defined as (/=) I believe. \$\endgroup\$
    – Tyler
    Commented Dec 18, 2012 at 8:25
  • 2
    \$\begingroup\$ Shorter solution would be to make an instance for (). \$\endgroup\$ Commented Jun 11, 2013 at 17:26
30
votes
\$\begingroup\$

Python

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

# Then (x == x+2) == True
\$\endgroup\$
6
  • \$\begingroup\$ Nice. All languages which support operator overloading can use similar solutions, but C isn't one of them. \$\endgroup\$
    – ugoren
    Commented Sep 6, 2012 at 10:05
  • \$\begingroup\$ 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 \$\endgroup\$
    – dr jimbob
    Commented Sep 6, 2012 at 17:21
  • \$\begingroup\$ A couple characters shorter if you dont extend from int.. class X:__add__=lambda s,o:s \$\endgroup\$
    – Doboy
    Commented Sep 15, 2012 at 4:55
  • \$\begingroup\$ May I ask what that multiplication does? \$\endgroup\$
    – seequ
    Commented Jun 5, 2014 at 15:25
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – grc
    Commented Jun 6, 2014 at 0:05
30
votes
\$\begingroup\$

GNU C supports structures with no members and size 0:

struct {} *x = 0;
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Very nice! I thought about pointer arithmetic with very large data leading to wraparound, but didn't think of the opposite. \$\endgroup\$
    – ugoren
    Commented Sep 7, 2012 at 15:13
25
votes
\$\begingroup\$

PHP:

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

Or:

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

Output:

bool(true)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I was actually trying to come up with this dead-simple PHP answer, but you beat me to it. \$\endgroup\$ Commented Sep 6, 2012 at 12:54
24
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ 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. \$\endgroup\$
    – ugoren
    Commented Sep 7, 2012 at 8:10
  • 3
    \$\begingroup\$ @ugoren thanks! If you want all this to be on one line, use COUNTER instead of LINE - requires GCC 4.3+ though. \$\endgroup\$
    – H2CO3
    Commented Sep 7, 2012 at 9:58
  • 1
    \$\begingroup\$ _CAT is reserved identifier. Anything that starts with underscore, and uppercase letter is reserved in C. \$\endgroup\$
    – null
    Commented Feb 21, 2014 at 7:13
  • \$\begingroup\$ @xfix that's exactly right, updated to remove UB. \$\endgroup\$
    – H2CO3
    Commented Feb 22, 2014 at 22:47
19
votes
\$\begingroup\$

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!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 0. Nope, still don't believe it. \$\endgroup\$
    – MSalters
    Commented Sep 7, 2012 at 11:59
  • \$\begingroup\$ @MSalters: What compiler do you use? You might have trigraphs disabled. \$\endgroup\$
    – vsz
    Commented Sep 7, 2012 at 21:31
  • \$\begingroup\$ VS2010. Quite possible that trigraphs are disabled by default. Either that or line concatenation doesn't work with ??\ \$\endgroup\$
    – MSalters
    Commented Sep 10, 2012 at 9:44
  • \$\begingroup\$ 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. \$\endgroup\$
    – vsz
    Commented Sep 10, 2012 at 19:58
17
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think you should explain what it does. Most people don't know Mathematica (or what Up Values are). \$\endgroup\$
    – ugoren
    Commented Sep 7, 2012 at 8:08
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Sep 7, 2012 at 17:41
16
votes
\$\begingroup\$

Javascript:

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

Test Fiddle

\$\endgroup\$
8
  • 2
    \$\begingroup\$ You could use Infinity, or -Infinity, and because of this you could use the shortcut of x = 1/0. \$\endgroup\$
    – zzzzBov
    Commented Sep 6, 2012 at 15:36
  • 6
    \$\begingroup\$ @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" :) \$\endgroup\$
    – Briguy37
    Commented Sep 6, 2012 at 15:49
  • \$\begingroup\$ 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. \$\endgroup\$
    – Alfe
    Commented Sep 7, 2012 at 12:19
  • 5
    \$\begingroup\$ @NicoBurns not ture :( \$\endgroup\$
    – ajax333221
    Commented Sep 8, 2012 at 22:27
  • 2
    \$\begingroup\$ @NicoBurns, running that code in the console produces false; wherever you're getting that info on JS is wrong and should not be trusted. \$\endgroup\$
    – zzzzBov
    Commented Sep 8, 2012 at 23:09
16
votes
\$\begingroup\$

scheme

(define == =)
(define (x a b c d) #t)
(x == x + 2)
;=> #t
\$\endgroup\$
4
  • \$\begingroup\$ Nice. Scheme's (x == x + 2) looks just like C's, but means a totally different thing. \$\endgroup\$
    – ugoren
    Commented Sep 7, 2012 at 15:07
  • 1
    \$\begingroup\$ Now do it for (= x 2). \$\endgroup\$
    – Joe Z.
    Commented Aug 15, 2013 at 16:40
  • \$\begingroup\$ (define (x a b c d) #t) :) \$\endgroup\$
    – Cruncher
    Commented Sep 30, 2014 at 15:11
  • \$\begingroup\$ @ugoren this is defined to do this by this program. x is simply a name of a function here. And so is == \$\endgroup\$
    – Cruncher
    Commented Sep 30, 2014 at 15:13
15
votes
\$\begingroup\$

Obvious answer:

When this terminates:

while (x != x+2) { }
printf("Now");
\$\endgroup\$
3
  • 1
    \$\begingroup\$ +1 meta.codegolf.stackexchange.com/a/1070/8766 but this is actually ingenious. \$\endgroup\$
    – user80551
    Commented Mar 10, 2014 at 14:06
  • 1
    \$\begingroup\$ I think while(!(x == x+2)) {} would be more in spirit \$\endgroup\$
    – Cruncher
    Commented Sep 30, 2014 at 15:15
  • \$\begingroup\$ This answer predates that meta post with two years. Everything that is considered a cliche today was novel at some point. \$\endgroup\$
    – daniero
    Commented Jul 25, 2017 at 15:24
14
votes
\$\begingroup\$

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);
\$\endgroup\$
1
  • \$\begingroup\$ 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). \$\endgroup\$
    – ugoren
    Commented Sep 6, 2012 at 12:21
13
votes
\$\begingroup\$

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

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

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Same trick works with PARI/GP \$\endgroup\$ Commented Sep 6, 2012 at 17:18
10
votes
\$\begingroup\$

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.

\$\endgroup\$
8
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ I really like this because it's the first answer to exploit float precision. \$\endgroup\$
    – AndrewKS
    Commented Sep 6, 2012 at 16:31
  • 1
    \$\begingroup\$ @AndrewKS: Actually Paul R was a bit earlier. \$\endgroup\$
    – MSalters
    Commented Sep 7, 2012 at 11:48
8
votes
\$\begingroup\$

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.

\$\endgroup\$
8
votes
\$\begingroup\$

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
\$\endgroup\$
7
votes
\$\begingroup\$

Perl

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

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

Output: true!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ sub x{} "works" as well.. (at least in my 5.10.1), but i can't figure why.. \$\endgroup\$
    – mykhal
    Commented Dec 16, 2012 at 8:27
  • 2
    \$\begingroup\$ 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); \$\endgroup\$
    – Perleone
    Commented Jan 20, 2013 at 1:00
  • \$\begingroup\$ That's awesome, @mykhal and @Perleone! \$\endgroup\$
    – memowe
    Commented Jan 20, 2013 at 14:07
7
votes
\$\begingroup\$

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.

\$\endgroup\$
6
votes
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • \$\begingroup\$ You can use std::boolalpha instead of ?:. \$\endgroup\$
    – Jon Purdy
    Commented Sep 6, 2012 at 17:58
5
votes
\$\begingroup\$

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
\$\endgroup\$
5
votes
\$\begingroup\$

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
\$\endgroup\$
4
votes
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – waldrumpus
    Commented Sep 6, 2012 at 12:27

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