When does (x == x+2)?

90

31

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.

ugoren

Posted 2012-09-06T09:05:02.293

Reputation: 16 527

Question was closed 2016-11-30T15:09:01.353

2Why are this question and all the answers Community Wiki? – mbomb007 – 2015-07-02T18:49:21.583

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 – 2012-09-07T11:45:10.097

1@JB, I don't hate the preprocessor. But it makes this specific question too easy. Without it, there's a challenge. – ugoren – 2012-09-07T15:11:06.293

29Why 4. Quick? You mean "Whoever knows one and is lucky enough to read this question first"? – Luc – 2012-09-07T21:43:22.717

@Luc, Basically yes. I think it's more fair than "the answer I like best", and I saw no better way to choose between the correct answers. – ugoren – 2012-09-08T19:49:18.827

6@ugoren Let the community vote (and vote yourself for ones you like), then choose the top answer after 7 days or so :) – Luc – 2012-09-08T21:48:39.037

1@Luc, I do let the community vote (and vote myself for ones I like). But as the question owner, I think I have the right to determine the accepted answer, regardless of the votes. – ugoren – 2012-09-09T06:59:55.017

It should be pretty trivial to define a class with overloaded operators that would take care of this. – Nicholas Hunsicker – 2012-09-15T18:10:43.430

3Regarding possibility 2: NaN doesn't work. NaN+2 is again NaN, but NaN==NaN is false. – Martin B – 2012-10-26T13:51:39.847

@MartinB, I guess you're right, fixed. You could make another question of it - when does x != x? – ugoren – 2012-10-27T10:05:37.427

Shame... in old versions of Sage, you could just set 2=0 – boothby – 2012-11-12T00:39:47.017

2The 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 – 2012-12-19T21:20:04.150

@userunknown, You're right, though I'd call it a sub-category of overloading. The main point is that + does something other than addition. – ugoren – 2012-12-20T05:25:22.643

Could x be declared as volatile int, and its memory location mapped to some device that decrements it by 2 the first time it is read? I guess this requires the C standard to specify a left-to-right order of evaluation for the operands of ==. I don't recall if it does (but I suspect that it leaves the order unspecified). – Psychonaut – 2016-04-04T15:38:41.570

When Jon Skeet. – It'sNotALie. – 2013-04-18T20:42:11.370

You can use bitfields like a one-bit data type, so actually it works with C – phuclv – 2014-06-04T05:05:16.803

does javascript x=NaN work? – Cruncher – 2014-09-30T15:07:52.863

Answers

71

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

Outputs 1.

Link: http://ideone.com/dL6A5

l0n3sh4rk

Posted 2012-09-06T09:05:02.293

Reputation: 1 387

7float x=1./0 is a bit shorter and perhaps more elegant. But anyway, this surely is the first good answer. – ugoren – 2012-09-06T10:37:33.797

1Ahh good old divide by zero. That took me longer to figure out than I'd like to admit. haha – Grant – 2012-09-07T07:11:42.913

Argh, I also though of this, but on Windows is doesn't compile so I dropped it. :( +1 though – Tudor – 2012-09-07T10:09:17.040

x=1e999 is another way of doing this. – shiona – 2012-09-08T15:36:01.557

4@shiona float x=1e20 would be enough – l0n3sh4rk – 2012-09-08T16:42:51.767

125

Fortran IV:

2=0

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

user1497298

Posted 2012-09-06T09:05:02.293

Reputation: 431

23All the more reason for me to never touch Fortran. – C0deH4cker – 2014-01-24T19:35:26.400

3Does it at least throw a warning? – Michael Stern – 2014-03-10T16:24:17.947

15@MichaelStern WARNING: YOU ARE CHANGING THE VALUE OF 2! – Cruncher – 2014-03-10T20:19:36.900

100

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.

PleaseStand

Posted 2012-09-06T09:05:02.293

Reputation: 5 369

3Certainly works, and I think it's the most elegant preprocessor based solution. But I think doing it without the preprocesor is more interesting. – ugoren – 2012-09-06T10:04:38.627

Is it just me or should 2|(0+2) be 1? – phunehehe – 2012-09-09T15:50:43.523

1

@phunehehe: | is bitwise OR; || is logical OR.

– PleaseStand – 2012-09-09T16:38:43.010

Uh, I thought it was /, silly me :"> – phunehehe – 2012-09-10T03:59:39.287

20This somehow reminds me of little Bobby Tables. – vsz – 2012-10-05T21:14:25.053

can anybody tell me how does (2|0 == 2|0+2) become (2|0 == 2|(0+2)) ? – rakeshNS – 2013-04-09T15:44:51.763

1

@rakeshNS: I added the extra set of parentheses to show operator precedence. That's why I said "Basically".

– PleaseStand – 2013-04-09T23:05:31.667

79

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.

ceased to turn counterclockwis

Posted 2012-09-06T09:05:02.293

Reputation: 5 200

12+1 Must be the most creative bending of the rules. – ninjalj – 2012-11-18T00:48:21.727

3Why do you need the x? – James – 2013-04-03T22:11:40.107

3@James The question says to define x so here x is defined as x. – user80551 – 2014-03-11T02:48:54.327

1@James the answer doesn't need anything except the + – Cruncher – 2014-09-30T15:07:20.963

56

F#

let (==) _ _ = true
let x = 0
x == (x + 2) //true

Daniel

Posted 2012-09-06T09:05:02.293

Reputation: 313

13I like this one. Instead of juggling numbers, simply redefine the meaning of == – evilcandybag – 2012-09-06T22:17:25.590

4Hang on, isn't the equality operator in F# simply =? == isn't even defined by default. – Jwosty – 2014-03-11T13:16:41.627

50

C

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

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

Paul R

Posted 2012-09-06T09:05:02.293

Reputation: 2 893

1@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. – Paul R – 2016-11-30T14:55:54.983

2@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 – GoatInTheMachine – 2016-11-30T15:20:38.720

1This 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 – chux - Reinstate Monica – 2017-05-03T18:21:52.117

@chux: thanks - I wasn't aware of FLT_EVAL_METHOD - out of interest, do you know of any platforms/environments where it's set to something other than 0 ? – Paul R – 2017-05-03T18:26:50.163

@PaulR float x = 1e10; printf("%d %d\n", x == x + 2, FLT_EVAL_METHOD); prints 0 2 on 64-bit PC "gcc version 5.4.0". x = 1e37f; works there as hoped. – chux - Reinstate Monica – 2017-05-03T18:28:59.560

@chux: interesting - so are both float_t and double_t typedef'd to long double in that environment ? ("all operations and constants evaluate in the range and precision of long double. Additionally, both float_t and double_t are equivalent to long double") – Paul R – 2017-05-03T18:33:02.233

@PaulR Do not use float_t much. C11 §7.12 2 confirms your comment and my printf("%d %zu %zu\n", FLT_EVAL_METHOD, sizeof (float_t), sizeof (long double)); --> 2 12 12 LSNED

– chux - Reinstate Monica – 2017-05-03T18:39:15.807

1@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. – Paul R – 2017-05-03T18:40:53.363

24+1 for real-world applications. Too many people don't understand floating point mathematics. – Tim S. – 2014-03-10T14:16:07.603

36

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

fjdumont

Posted 2012-09-06T09:05:02.293

Reputation: 151

4Dang it, just got a 'Nice Answer' badge for this post. Seriously, getting badges for EVIL stuff?! Don't do this at home! – fjdumont – 2013-04-19T09:22:17.690

It's evil, but it's so beautiful... – Kevin – 2014-03-10T20:17:06.937

32

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.

Petr Pudlák

Posted 2012-09-06T09:05:02.293

Reputation: 4 272

3You can simplify: fromInteger = odd – Rotsor – 2012-09-08T02:54:32.297

1Also (+) can be defined as (/=) I believe. – MatrixFrog – 2012-12-18T08:25:54.260

2Shorter solution would be to make an instance for (). – Thomas Eding – 2013-06-11T17:26:32.583

31

Python

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

# Then (x == x+2) == True

grc

Posted 2012-09-06T09:05:02.293

Reputation: 18 565

Nice. All languages which support operator overloading can use similar solutions, but C isn't one of them. – ugoren – 2012-09-06T10:05:27.440

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 – 2012-09-06T17:21:42.513

A couple characters shorter if you dont extend from int.. class X:__add__=lambda s,o:s – Doboy – 2012-09-15T04:55:05.693

May I ask what that multiplication does? – seequ – 2014-06-05T15:25:22.377

2

@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 – 2014-06-06T00:05:11.433

Ah. I forgot that completely. – seequ – 2014-06-06T07:40:44.710

31

GNU C supports structures with no members and size 0:

struct {} *x = 0;

han

Posted 2012-09-06T09:05:02.293

Reputation: 1 226

2Very nice! I thought about pointer arithmetic with very large data leading to wraparound, but didn't think of the opposite. – ugoren – 2012-09-07T15:13:52.623

26

PHP:

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

Or:

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

Output:

bool(true)

Dzhuneyt

Posted 2012-09-06T09:05:02.293

Reputation: 231

1I was actually trying to come up with this dead-simple PHP answer, but you beat me to it. – PleaseStand – 2012-09-06T12:54:04.817

25

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.

H2CO3

Posted 2012-09-06T09:05:02.293

Reputation: 241

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 – 2012-09-07T08:10:30.307

3@ugoren thanks! If you want all this to be on one line, use COUNTER instead of LINE - requires GCC 4.3+ though. – H2CO3 – 2012-09-07T09:58:57.290

1_CAT is reserved identifier. Anything that starts with underscore, and uppercase letter is reserved in C. – Konrad Borowski – 2014-02-21T07:13:32.893

@xfix that's exactly right, updated to remove UB. – H2CO3 – 2014-02-22T22:47:22.087

20

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!

vsz

Posted 2012-09-06T09:05:02.293

Reputation: 7 963

10. Nope, still don't believe it. – MSalters – 2012-09-07T11:59:21.680

@MSalters: What compiler do you use? You might have trigraphs disabled. – vsz – 2012-09-07T21:31:16.327

VS2010. Quite possible that trigraphs are disabled by default. Either that or line concatenation doesn't work with ??\ – MSalters – 2012-09-10T09:44:16.283

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 – 2012-09-10T19:58:48.920

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.

Carl Morris

Posted 2012-09-06T09:05:02.293

Reputation: 121

1I think you should explain what it does. Most people don't know Mathematica (or what Up Values are). – ugoren – 2012-09-07T08:08:00.683

1Thank 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 – 2012-09-07T17:41:49.757

17

Javascript:

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

Test Fiddle

Briguy37

Posted 2012-09-06T09:05:02.293

Reputation: 2 616

2You could use Infinity, or -Infinity, and because of this you could use the shortcut of x = 1/0. – zzzzBov – 2012-09-06T15:36:32.790

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 – 2012-09-06T15:49:26.237

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 – 2012-09-07T12:19:53.940

Smaller: x="";alert(x==x+2). == in javascript always compares two strings as true. – Nico Burns – 2012-09-08T15:53:55.640

5@NicoBurns not ture :( – ajax333221 – 2012-09-08T22:27:05.590

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 – 2012-09-08T23:09:35.137

I stand corrected. I did try this out in the chrome console to test it, but I must have done something wrong as I am also getting false now. – Nico Burns – 2012-09-09T15:39:18.373

@NicoBurns You must have been caught by the fact most dynamic languages evaluate strings to true in an if statement (as in if('string')...), or some other kind of type juggling. But different strings are != between each other. – Camilo Martin – 2013-12-19T14:23:12.660

17

scheme

(define == =)
(define (x a b c d) #t)
(x == x + 2)
;=> #t

user1651640

Posted 2012-09-06T09:05:02.293

Reputation: 51

Nice. Scheme's (x == x + 2) looks just like C's, but means a totally different thing. – ugoren – 2012-09-07T15:07:09.887

1Now do it for (= x 2). – Joe Z. – 2013-08-15T16:40:38.910

(define (x a b c d) #t) :) – Cruncher – 2014-09-30T15:11:15.933

@ugoren this is defined to do this by this program. x is simply a name of a function here. And so is == – Cruncher – 2014-09-30T15:13:59.817

16

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

PleaseStand

Posted 2012-09-06T09:05:02.293

Reputation: 5 369

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 – 2012-09-06T12:21:22.287

16

Obvious answer:

When this terminates:

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

daniero

Posted 2012-09-06T09:05:02.293

Reputation: 17 193

This answer predates that meta post with two years. Everything that is considered a cliche today was novel at some point. – daniero – 2017-07-25T15:24:12.253

1

+1 http://meta.codegolf.stackexchange.com/a/1070/8766 but this is actually ingenious.

– user80551 – 2014-03-10T14:06:48.930

1I think while(!(x == x+2)) {} would be more in spirit – Cruncher – 2014-09-30T15:15:59.467

14

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

int (*x)[0x2000000000000000];

han

Posted 2012-09-06T09:05:02.293

Reputation: 1 226

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 – 2012-09-07T15:12:59.020

@ugoren, it works for me, on Linux with 4-byte int. – han – 2012-09-07T16:07:41.833

You're absolutely right. I missed the fact that it's an array of int, not char. – ugoren – 2012-09-07T20:25:02.470

10

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

dspyz

Posted 2012-09-06T09:05:02.293

Reputation: 875

1Same trick works with PARI/GP – Hagen von Eitzen – 2012-09-06T17:18:00.693

10

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.

J B

Posted 2012-09-06T09:05:02.293

Reputation: 9 638

8

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.

marinus

Posted 2012-09-06T09:05:02.293

Reputation: 30 224

I really like this because it's the first answer to exploit float precision. – AndrewKS – 2012-09-06T16:31:22.487

1@AndrewKS: Actually Paul R was a bit earlier. – MSalters – 2012-09-07T11:48:34.257

8

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.

Konrad Borowski

Posted 2012-09-06T09:05:02.293

Reputation: 11 185

8

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

jsvk

Posted 2012-09-06T09:05:02.293

Reputation: 107

7

Perl

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

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

Output: true!

memowe

Posted 2012-09-06T09:05:02.293

Reputation: 409

1sub x{} "works" as well.. (at least in my 5.10.1), but i can't figure why.. – mykhal – 2012-12-16T08:27:03.207

2Because 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 – 2013-01-20T01:00:29.053

That's awesome, @mykhal and @Perleone! – memowe – 2013-01-20T14:07:41.523

7

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.

Jens Timmerman

Posted 2012-09-06T09:05:02.293

Reputation: 151

6

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

PleaseStand

Posted 2012-09-06T09:05:02.293

Reputation: 5 369

You can use std::boolalpha instead of ?:. – Jon Purdy – 2012-09-06T17:58:33.180

5

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

AndrewKS

Posted 2012-09-06T09:05:02.293

Reputation: 121

5

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

tb-

Posted 2012-09-06T09:05:02.293

Reputation: 101

4

Java

double x = Double.POSITIVE_INFINITY; // Double.NEGATIVE_INFINITY also works
System.out.println(x == x + 2);      // prints true

rodrigopc

Posted 2012-09-06T09:05:02.293

Reputation: 11

This is essentially the same as the accepted answer at http://codegolf.stackexchange.com/a/7169/12205

– user12205 – 2014-02-20T21:45:11.950

4

Common Lisp

(let ((x   42)
      (x+2 42))
  (= x x+2))
;=> true

Joshua Taylor

Posted 2012-09-06T09:05:02.293

Reputation: 660

4

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

PleaseStand

Posted 2012-09-06T09:05:02.293

Reputation: 5 369

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 – 2012-09-06T12:27:44.210

4

Ada

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.

Alexis Wilke

Posted 2012-09-06T09:05:02.293

Reputation: 133

3

Bash (0 character)

According to the rule, it looks like I can suggest my 0 character definition of x in bash, since without any definition, I have:

if (x==x+2); then echo "true"; fi

Output

true

Is it fair?

Thomas Baruchel

Posted 2012-09-06T09:05:02.293

Reputation: 1 590

1You need the expression x == x+2 to evaluate to true in some way. What you are doing is trying to output true regardless of the comparison result. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-11T12:07:07.007

Your comment and downvote isn't totally fair; my piece of bash code is merely here for proving the test is true (because bash doesn't display 'true' by itself); if you replace the expression with something evaluating to false, the result will be different: if false; then echo "true"; fi – Thomas Baruchel – 2014-03-11T12:40:18.633

Sorry, I misunderstood your code. What you actually do is define x to be =x+2, and the definition is always true (the rule allows this, since it shows an interesting aspect of the language). I mistakenly thought the true on its own is a command. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-11T12:49:37.030

3

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

DarkTygur

Posted 2012-09-06T09:05:02.293

Reputation: 36

3

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

jncraton

Posted 2012-09-06T09:05:02.293

Reputation: 101

3

C

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

olivecoder

Posted 2012-09-06T09:05:02.293

Reputation: 307

3

C

let the computer find a value for x

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

gnibbler

Posted 2012-09-06T09:05:02.293

Reputation: 14 170

3

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

mroman

Posted 2012-09-06T09:05:02.293

Reputation: 1 382

3

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.

Douglas S. Stones

Posted 2012-09-06T09:05:02.293

Reputation: 101

2

JavaScript

x=Math.log(0)
x==x+2

Prints

True

Oliver

Posted 2012-09-06T09:05:02.293

Reputation: 7 160

2

Tcl, 22 chars.

proc (x args return\ 1

Johannes Kuhn

Posted 2012-09-06T09:05:02.293

Reputation: 7 122

I don't know tcl but where is x+2 here? – phuclv – 2014-06-04T05:01:01.920

if you execute (x == x+2) after that, it will return 1. – Johannes Kuhn – 2014-06-09T22:40:29.323

2

J

x =: 1

There is no == operator in J, sox==x+2 would actually mean x=(=(x+2)). Unary = is an operator, that will return 1 acting on any number, and as binary it is just an equality. So 1=(=(1+2)) => 1=(=3) => 1=1 => 1.

swish

Posted 2012-09-06T09:05:02.293

Reputation: 7 484

2

SWI-Prolog

In query mode:

?- X = X+2, X == X+2.
X = X+2.

You just need to "assign" X = X + 2, then X == X + 2 will be true. Why make things so complicated?


Real explanation

In Prolog, x is an atom, so it is not possible to make x == x + 2 returns true. Variables in Prolog must start with an uppercase letter or underscore.

Therefore, my solution will define (uppercase) X so that X == X+2.

In Prolog, == compares 2 terms according to standard order of terms. Therefore, we only need to unify (= operator) X and X+2 before doing the comparison.

Note that the unification X = X+2 unifies X with the infinite term X = (((...)+2)+2)+2, much like how the unification X = f(X) unifies X with the infinite term X = f(f(f(...))).

In Prolog, when a query succeeds, it will return true if there is no variable, or it will return the variable binding which satisfies the query. This explains the output X = X+2.

n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Posted 2012-09-06T09:05:02.293

Reputation: 5 683

2

PHP

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

Works in many other languages as well.

primo

Posted 2012-09-06T09:05:02.293

Reputation: 30 891

2

Ruby

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

intellidiot

Posted 2012-09-06T09:05:02.293

Reputation: 121

2

Scala

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

x == x + 2
//res0: Boolean = true

Landei

Posted 2012-09-06T09:05:02.293

Reputation: 109

2

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.

Roberto Mereghetti

Posted 2012-09-06T09:05:02.293

Reputation: 111

2

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

user5423

Posted 2012-09-06T09:05:02.293

Reputation:

shouldn't x be promoted to int in expresseon x+2? – Vovanium – 2014-06-10T16:37:39.513

1

Python

>>> x=1e999
>>> x==x+2
True

jamylak

Posted 2012-09-06T09:05:02.293

Reputation: 420

1

Haskell

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

Calling f with any argument (whose type is in the Eq typeclass) will evaluate to True.

Strigoides

Posted 2012-09-06T09:05:02.293

Reputation: 1 025

1

Missing GolfScript?

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

aditsu quit because SE is EVIL

Posted 2012-09-06T09:05:02.293

Reputation: 22 326

Because in GS you can't write x == x+2 with any sense... Nice idea though, does it redefine 2? – tomsmeding – 2013-05-06T04:48:35.033

@tomsmeding well the syntax is different, but you can write e.g. x.2+= and yes, basically it does "2=0". – aditsu quit because SE is EVIL – 2013-05-06T06:11:49.800

1

JavaScript

var x = Infinity;

So if you add anything to infinity it will remain infinity.

Digvijay Yadav

Posted 2012-09-06T09:05:02.293

Reputation: 99

1

Trying to come up with something that doesn't fall under one of the existing seven groups is tough:

def x
  rand(1..3)
end

puts x==x+2

33% of the time, it's right all the time...

jzig

Posted 2012-09-06T09:05:02.293

Reputation: 71

1I get 100% of the time “TypeError: can't convert Range into Integer”. (At least with Ruby 1.9.2.) In case you correct the syntax to rand 3 (that will result range 0..2, but should not matter for the result), you will get 11.11% correct answers. That is because you are comparing 2 random numbers and both have to take a certain value: the 1st number must be 0 and the 2nd 2. The 1st will be 0 in 33.33% of the tries, the 2nd will be 2 also in 33.33% of the tries. The 1st will be 0 and the 2nd will be 2 in 11.11% of the tries. – manatwork – 2013-06-09T12:13:37.147

1Ha, yeah I was joking about the statistic - I knew it would be calling rand twice. I was just grasping at straws for something 'different'. Kernel#rand accepts ranges in 1.9.3 – jzig – 2013-06-09T23:48:16.970

Thanks for the version information. Didn't knew that. – manatwork – 2013-06-10T05:30:55.350

1

$x == $х+2 for infinite pairs of numbers. Let's try it out.

PHP

$х = 1;
$x = 3;

if ($x == $х+2)
    echo "LOL it works. Sort of black magic?";

Nah, it's not black magic. Truth is that one x is Kha, that as Wikipedia states, it looks the same as the Latin letter X, in both uppercase and lowercase, both roman and italic forms.

There's actually no difference between them, so even if there are two different variables, rules are not broken, since I assumed that a x is a Kha.

Vereos

Posted 2012-09-06T09:05:02.293

Reputation: 4 079

1

C

Defining x as 1==-2

#include<stdio.h>
#define x 1==-2

main()
{
  printf("%d", (x==x+2) ) ;
}

user80551

Posted 2012-09-06T09:05:02.293

Reputation: 2 520

1

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.

Pieter Witvoet

Posted 2012-09-06T09:05:02.293

Reputation: 201

1

ECMAScript (also known as JavaScript):

x=1e17

Toothbrush

Posted 2012-09-06T09:05:02.293

Reputation: 3 197

1

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

Flonk

Posted 2012-09-06T09:05:02.293

Reputation: 7 621

1

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

ForemanBob

Posted 2012-09-06T09:05:02.293

Reputation: 61

1

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)

fa wildchild

Posted 2012-09-06T09:05:02.293

Reputation: 111

1

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

Wahyu Kristianto

Posted 2012-09-06T09:05:02.293

Reputation: 101

1

Python:

>>> x=float('inf')
>>> x==x+2
True

Ashwini Chaudhary

Posted 2012-09-06T09:05:02.293

Reputation: 169

1

Haskell

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

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

Adam Wagner

Posted 2012-09-06T09:05:02.293

Reputation: 101

1

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.

Mr Lister

Posted 2012-09-06T09:05:02.293

Reputation: 3 668

Nice idea but I don't the think the order of evaluation for your x=x+2 expression is guaranteed, so whether this works or not will be compiler-dependent. – Paul R – 2013-06-09T07:32:08.437

0

Mathematica

x=∞

Mathematica is perfectly happy to reason (within reason) with infinity, and knows that and ∞+2 are the same!

Greg Martin

Posted 2012-09-06T09:05:02.293

Reputation: 13 940

0

ForceLang

def x set y -2+y
io.write x=x+2

SuperJedi224

Posted 2012-09-06T09:05:02.293

Reputation: 11 342

0

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

Ben Reich

Posted 2012-09-06T09:05:02.293

Reputation: 1 577

0

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.

PyRulez

Posted 2012-09-06T09:05:02.293

Reputation: 6 547

0

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

draegtun

Posted 2012-09-06T09:05:02.293

Reputation: 1 592

0

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.

md_rasler

Posted 2012-09-06T09:05:02.293

Reputation: 201

0

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

CompuChip

Posted 2012-09-06T09:05:02.293

Reputation: 439

0

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;

CompuChip

Posted 2012-09-06T09:05:02.293

Reputation: 439

0

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

xem

Posted 2012-09-06T09:05:02.293

Reputation: 5 523

0

JavaScript

var x = {y: 0, toString: function() {return (this.y+=2)}};
console.log(x == x+2); // true

When you add number to an object you indirectly call toString method of this object. toString method returns number... Right side becomes number, then == operator converts x to primitive by using it's toString method.

Interesting article about related idea: Fake operator overloading in JavaScript.

Ginden

Posted 2012-09-06T09:05:02.293

Reputation: 197

0

Python (18)

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

Gives True in interactive mode.

jur

Posted 2012-09-06T09:05:02.293

Reputation: 171

0

J

   x=:!123
   x=x+2
1

This is also reliant on the floating point trick: !123x=2+!123x returns 0(= actually is the comparison operator, so no trickery there)

Or, maybe even better:

   x=:_
   x=x+2
1

simply sets x to infinity.

ɐɔıʇǝɥʇuʎs

Posted 2012-09-06T09:05:02.293

Reputation: 4 449

0

Javascript

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

This doesn't work in strict mode, nor without a global variable (i.e window). Tested in Firefox 38.

Afonso Matos

Posted 2012-09-06T09:05:02.293

Reputation: 312

0

Ruby

With some monkey patching, everything is possible.

class Fixnum
    def ==(obj)
        # Check if difference between self and obj is 0, -2 or +2
        "#{self-obj}"=~/0|\-?2/ ? true : false
    end
end

As I can't use self==obj || self==obj+2 || self==obj-2, as that would cause a StackError, I first transform them into Strings, then check if the difference matches "0", "-2" or "2"

Test cases

# Make sure `x` is from type Fixnum
x=0

p (x==x+2) # => true
p (x+2==x) # => true
p (x==x)   # => true
p (x==x+1) # => false
p (x==x+3) # => false

Charlie

Posted 2012-09-06T09:05:02.293

Reputation: 691

0

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

WIldWorldDev

Posted 2012-09-06T09:05:02.293

Reputation: 11

Infinity is an answer, but not the only one (as you can see here). – ugoren – 2012-09-07T08:14:05.043

0

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 

Fivell

Posted 2012-09-06T09:05:02.293

Reputation: 99

0

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> 

Brian

Posted 2012-09-06T09:05:02.293

Reputation: 1

0

Processing

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

The output will be true

Not very creative, but yeah.

Rob

Posted 2012-09-06T09:05:02.293

Reputation: 1 277

0

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

phtrivier

Posted 2012-09-06T09:05:02.293

Reputation: 101

0

Python

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

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

Chris Kemp

Posted 2012-09-06T09:05:02.293

Reputation: 1

0

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.

Bendoh

Posted 2012-09-06T09:05:02.293

Reputation: 101

0

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

tomcant

Posted 2012-09-06T09:05:02.293

Reputation: 11

0

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

boothby

Posted 2012-09-06T09:05:02.293

Reputation: 9 038

class foo(int):__cmp__=lambda*a:0 is easier – gnibbler – 2012-09-11T20:11:43.080

@gnibbler, I'd agree if addition didn't raise an exception. – boothby – 2012-09-13T04:48:38.377

Which version of Python are you using? It doesn't raise an exception on 2.7.3 – gnibbler – 2012-09-13T06:21:48.630

@gnibbler, ooh, I missed the (int). sneaky sneaky. don't know that I'd call it 'easier'. – boothby – 2012-09-14T05:26:12.750

well it's easier because you get to support 2+x for free – gnibbler – 2012-09-14T05:43:21.247

@gnibbler, but I get out of defining a compare! – boothby – 2012-09-15T10:19:09.173

0

Python

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

x=9e9**9
x==x+2

gnibbler

Posted 2012-09-06T09:05:02.293

Reputation: 14 170

0

q/k

Pretty trivial using infinity (or null):

q)x:0w

x=x+2
1b

skeevey

Posted 2012-09-06T09:05:02.293

Reputation: 4 139

0

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

mroman

Posted 2012-09-06T09:05:02.293

Reputation: 1 382

0

Sage

sage: print oo
+Infinity
sage: oo+2==oo
True

boothby

Posted 2012-09-06T09:05:02.293

Reputation: 9 038

0

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

Will Lp

Posted 2012-09-06T09:05:02.293

Reputation: 797

0

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

gnibbler

Posted 2012-09-06T09:05:02.293

Reputation: 14 170

1

@han already suggested exactly the same.

– ugoren – 2012-09-19T07:42:08.640

0

Coffeescript, 18 chars

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

Clyde Lobo

Posted 2012-09-06T09:05:02.293

Reputation: 1 395

0

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

PleaseStand

Posted 2012-09-06T09:05:02.293

Reputation: 5 369

-4

JavaScript

!!("x==x+2") // true

xem

Posted 2012-09-06T09:05:02.293

Reputation: 5 523

1Can you really say this is defining x? – Jonathan Van Matre – 2014-03-10T15:23:32.077

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Jonathan Van Matre – 2014-03-10T15:23:56.963

it was just a joke. – xem – 2014-03-10T19:28:16.797

-4

 cout << bool(x == x+2);

! is not needed at all

bla2e

Posted 2012-09-06T09:05:02.293

Reputation: 17

It outputs 1, which means x == x+2 is false. I want x == x+2 to be true. – ugoren – 2012-09-06T12:51:15.250

yeah, sorry, fixed :D – bla2e – 2012-09-06T14:08:12.873

I still don't get it. x == x+2 is false in this case. – ugoren – 2012-09-07T08:06:26.333

DevC++ says that it is true – bla2e – 2012-09-07T09:03:06.863

I don't have DevC++ at hand, so could you please detail in the comments how/why that's possible? – J B – 2012-09-07T11:43:34.327

1It depends on the initialization of x, which isn't shown. So, no points for this answer. – MSalters – 2012-09-07T11:51:40.943

#include <iostream> using namespace std; int main (){ int x=5; cout << bool(x == x+2); } Works in DevC++. The reason is that the bool function is not looking for that expression to be true, it just looks if there an expression, if there is one, it is true, if no, it is false, imho – bla2e – 2012-09-07T16:14:23.463

@bla2e, this means your solution is wrong. I want x == x+2 to be true. Your code just checks that it exists. – ugoren – 2012-09-07T20:22:48.477

The answer u set as best, is not even dealing with variables, double x=1.0/0.0; – bla2e – 2012-09-08T00:28:59.000