Write a program that makes 2 + 2 = 5

393

225

Write a program that seemingly adds the numbers 2 and 2 and outputs 5. This is an underhanded contest.

Your program cannot output any errors. Watch out for memory holes! Input is optional.

Redefining 2+2 as 5 is not very creative! Don't doublethink it, try something else.

qwr

Posted 2014-05-30T06:54:35.963

Reputation: 8 929

Question was closed 2016-03-23T04:50:34.733

Sadly, I don't have enough reputation to post, but I really wanted to post something. First off, this is probably invalid ;-; but here's my Brainf*** code, which sizes in at 63 bytes:

++++[>++++[>+++<-]<-]>>++.-------.+++++++.+++++++++++.--------. – EnragedTanker – 2015-03-04T16:16:20.503

I'm closing this question in compliance with our policy on underhanded challenges.

– Dennis – 2016-03-23T04:50:34.733

48This is question in book "1984" by George Orwelll. – bacchusbeale – 2014-05-30T12:23:22.157

97Why is this underhanded? Two plus two is five. – Geobits – 2014-05-30T16:23:03.263

1http://www.youtube.com/watch?v=lstDdzedgcE – Flonk – 2014-05-30T16:29:07.177

79THERE! ARE! FOUR! LIGHTS! – Nick T – 2014-05-30T19:57:02.437

105

@Geobits - I agree: 2+2=5 you can see it in this calculator.

– MT0 – 2014-05-30T20:03:40.280

47echo "2+2=5"; – user3459110 – 2014-05-31T12:16:21.537

34I always thought that 2 + 2 = 5 for very large values of 2. – devnull – 2014-06-01T02:55:47.440

6(1<<2)+(2>>1) – gnibbler – 2014-06-01T13:53:42.407

1Big Brother? NOT ROOM 101 :( – Max00355 – 2014-06-01T14:45:05.610

2Python: >>> 1 + 2e-60 + 2e-60 == 1+ 5e-60 True – Danra – 2014-06-01T20:28:34.110

2

To see discussions of this question and its answers: Reddit and Hacker News.

– None – 2014-06-02T02:28:47.537

1C/C++ char flush[] = "\n \003"; printf("%d\n", 2 + 2 [flush]); – Tony D – 2014-06-02T03:06:33.567

#include <stdio.h>

int main(int argc, char** argv) {
char c = '2'; int a = (int)c; printf("%c+%c=%d\n", c, c, a/10)); return 0; } – Alex Reynolds – 2014-06-02T07:35:26.317

2(function () { var two = 2; console.log(two+++two); })(); – Growler – 2014-06-02T16:03:25.503

@MT0 I thought you were referring to this 100% accurate model

– iFreilicht – 2014-06-02T22:09:05.093

1

In Swift: http://oi60.tinypic.com/blu8o.jpg

– janjarfalk – 2014-06-03T01:22:20.527

Not enough reputation for a post, so C# alternative is here: int x = 2, y = 2; Action action = () => Console.WriteLine(x + y); x++; action();. Not working in .Net 4.5+ – Alex Zhukovskiy – 2014-06-04T10:32:32.827

1@MichaelT I can't believe my question made it to reddit, haha – qwr – 2014-06-05T05:17:57.443

1int i = 2 + 2; Console.Write(++i); C# – sangram parmar – 2014-06-06T08:19:13.337

The teacher Jonofon Serates shows an way to do it mathematically https://www.youtube.com/watch?v=xanIFMTxKGs it is in Portuguese, anyway the math is the same in any language :D

– ademar111190 – 2014-06-06T15:37:00.733

2Drat. I have a really short FORTRAN answer that actually happened to me once, but not enough reputation to add it. – DJClayworth – 2014-06-08T19:54:01.563

Answers

669

Java

Reflection is indeed the right way to go with abusing Java... but you need to go deeper than just tweaking some values.

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] array = (Integer[]) c.get(cache);
        array[132] = array[133];

        System.out.printf("%d",2 + 2);
    }
}

Output:

5

Explanation:

You need to change it even deeper than you can typically access. Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the IntegerCache.

Deep within the Integer class is a Flyweight of Integers. This is an array of Integers from −128 to +127. cache[132] is the spot where 4 would normally be. Set it to 5.

Warning: Doing this in real code will make people very unhappy.

Code demo on ideone.

user12166

Posted 2014-05-30T06:54:35.963

Reputation:

1@Cruncher so you are giving votes because he is receiving votes? When does it end? – Cyoce – 2016-01-05T16:05:38.930

@Cyoce When there's noone else to vote? And other people that don't share my sentiment? lol. I do only count for one vote ya know ;) – Cruncher – 2016-01-05T16:48:15.420

5Thought of this one as soon as I saw the question :) – Octavia Togami – 2014-05-30T17:14:07.820

306That. Is. Evil. Absolutely evil. +1 – John Dvorak – 2014-05-30T17:45:31.463

75

@JanDvorak in chat it was suggested Integer[] array = (Integer[]) c.get(cache); fisherYatesShuffle(array); Just imagine how many things would break...

– None – 2014-05-30T17:57:44.927

1@MichaelT this got me thinking about a new kind of russian roulette ;-) – John Dvorak – 2014-05-30T17:58:33.350

4Since you're already using reflection, you could easily make this independent of the cache size (which does depend on runtime flags after all): Field f = Integer.class.getDeclaredField("value"); f.setAccessible(true); f.set(4, 5) Could be made even more reliable by just grabbing the first non-static field - any reasonable implementation will only have a single field after all. – Voo – 2014-05-30T20:27:13.033

30Answers like this make me love this site more than SO. – Songo – 2014-05-30T21:33:58.337

4@Voo true, and I did consider that a bit. However, its not quite as subtle/underhanded... the code above doesn't even use the digits 4 or 5. – None – 2014-05-30T23:29:18.383

1@Michael Fair point, considering the goal of making it underhanded. So right you are, way less obvious this way – Voo – 2014-05-30T23:59:41.823

3@MichaelT Collections.shuffle(Arrays.asList(array)); – Alvin Wong – 2014-05-31T10:16:02.080

1To make this underhanded, the manipulation has to be hidden a bit more. – Paŭlo Ebermann – 2014-05-31T22:15:05.873

@MichaelT I'm new to Java, can you explain why this ability exists at all? Seems dangerous to leave in a language. – qwr – 2014-06-01T00:33:31.250

4

@qwr reflection belongs to a type of programming known as metaprograming - writing programs about structures within the language. That type of thing exists in many languages and is a key part of how some things are done. You can see similar things in python and can be used to do some really neat things but that comes at the cost of being able to do dangerous stuff.

– None – 2014-06-01T00:55:40.857

@qwr as an aside, I'm frequently in The Whiteboard chat room of Programmers.SE and would be more than happy to go through some of the uses of metaprogramming in Java (there are really neat things you can do with it if you use a 'safer' approach of annotations with libraries that understand them (rather than just poking around in the innards of a class)).

– None – 2014-06-01T00:58:13.347

2It is very sad that one can do this. – Sebastian Godelet – 2014-06-01T08:14:57.287

4evil.js, evil.sh, evil.css and evil.java – Léo Lam – 2014-06-01T10:22:36.260

1@SebastianGodelet there are a number of design choices that facilitate this, all for very good reasons. Metaprogramming that allows for advanced debuggers, introspection, and libraries. A Flyweight pattern in the Integer for performance when boxing and reduce memory usage. And a varargs structure allowing for variable length parameter lists (but then must be Objects rather than primitives). This combination of design choices can allow someone to poke in places they shouldn't but also allows for much more powerful programs and libraries. – None – 2014-06-01T12:51:22.030

I just love Java's reflection. Way more freedom than .NET world. – Mohammad Banisaeid – 2014-06-02T07:28:59.270

3Anyone intending to do this should make sure to only have this happen a small fraction of the time. And then make sure to add a check in front of one of your statements something like "if 2+2= 5 then" with some comment about "for some reason sometimes 2+2=5, this accounts for these situations" so anyone reading it in the future is confused even more. – enderland – 2014-06-02T13:19:13.723

35zomg, java answers never get top votes! +1 for bringing java to the top :) – Cruncher – 2014-06-02T16:20:24.490

1

@enderland The dailyWTF munger program does just that, constantly reconfigures Integers

– Richard Tingle – 2014-06-03T09:06:04.687

There are other Java reflection tricks, like changing immutable strings. The internal functionality of the String class has changed slightly over the years, but this should still be possible.

– None – 2014-06-06T15:32:14.040

@JohnGaughan there was an answer that did that though I can't seem to find it (I thought it was a good one) and exposes some interesting bits on how String interning worked and where things where done when. That said, I'm still quite pleased with this approach because of its lack of use of the numbers 4 and 5 in the code. – None – 2014-06-06T15:34:47.033

With this, any calculation that would normally result in 4 will result in 5 correct? 1 + 3 = 5, 4 * 1 = 5, 2 * 2 = 5, 9 - 5 = 5... – Mr.Mindor – 2014-06-09T20:49:46.573

@Mr.Mindor when cast to an Integer either with autoboxing or valueOf() - yes. I change the value of the entry where 4 sits in the IntegerCache class to be the same as 5 and anything that uses that will have the value of 5. – None – 2014-06-10T02:05:44.267

1Changing the value of a constant? Java emulating old FORTRAN! This is the final proof that real programmers can write FORTRAN in any language ;-) – celtschk – 2014-06-12T21:33:16.783

So, sometimes Java lets you do crazier things than you could do in LISP... – Reinstate Monica – 2014-08-21T15:00:09.160

Interestingly, printf("%d",2+2) prints 5, but System.out.println(2+2) prints 4. Can anyone offer any insight into what's going on there? – Davis Yoshida – 2014-08-29T18:58:45.863

1

@DavisYoshida printf(String format, Object... args) takes an Object array while println(int x) takes an int. Thus, the value returned by 2+2 must be cast to an Object (an Integer in this case) by being auto boxed using valueOf(2+2). Look at valueOf and the cache.

– None – 2014-08-29T19:03:46.410

297

Haskell

I just love how you can throw anything at ghci and it totally rolls with it.

λ> let 2+2=5 in 2+2
5

Flonk

Posted 2014-05-30T06:54:35.963

Reputation: 7 621

36What does let 2+2=5 in 5+5 do? ಠ_ಠ – John Dvorak – 2014-05-30T17:44:32.753

2Define function named 2+2 that return 5 – Hauleth – 2014-05-30T17:47:30.350

22@JanDvorak Non-exhaustive patterns in function + - I'm defining a new function (+) here, and If I plug in anything that isn't 2+2 it will error because I never defined what should happen in that case. – Flonk – 2014-05-30T17:50:24.173

@Flonk I got it. That's why I used my look of disapproval ;-) – John Dvorak – 2014-05-30T17:53:01.690

1@JanDvorak haha, okay ಠ_ಠ – Flonk – 2014-05-30T17:59:28.447

6The plus operator is a function, and let can redefine existing functions. let (+) 2 2 = 5 in (+) 2 2 – Ming-Tang – 2014-05-30T18:31:47.127

27@SHiNKiROU shadow, not redefine – John Dvorak – 2014-05-30T18:33:59.003

96that almost sounds like: "And God said let 2+2=5 in 2+2" )) – OutFall – 2014-05-30T23:15:36.473

4@N0ir unfortunately, Genesis doesn't make for a valid Haskell code. Not even the first chapter. Not even the verse you mention. – John Dvorak – 2014-05-31T06:02:28.113

6

I'm a fan of the where version: 2 + 2 where 2 + 2 = 5. It even pops up on t-shirts! It doesn't work in GHCi though :(.

– Tikhon Jelvis – 2014-06-01T15:48:18.293

10let 2+2=5; x+y= x Prelude.+ y in 5+5 only redefines 2+2 and leaves the rest of addition alone. – Davorak – 2014-06-01T15:54:55.870

How does this even work? How is this actually allowed?! – user3217013 – 2014-06-02T01:41:18.163

11@user3217013 Learn Haskell, it's good for your heart. – Shoe – 2014-06-02T02:19:12.963

@Jefffrey Thanks for your condescending comment, but I am actually well-versed in Haskell. I just have never seen this pattern before. – user3217013 – 2014-06-02T02:27:58.410

1@user3217013 You are just defining the function (+) using equational style, where you define what should happen when the first argument is 2 and the second is 2, and you don't define all the other cases (thus, an inexhaustive definition). Kind of case (x, y) of (2, 2) -> 5 – Ptival – 2014-06-02T02:47:50.047

@user3217013 A let expression in Haskell defines a local variable to a specified value within the context of that expression. But "variable" here in fact encompasses not just things like x and y, but also infix operators like +, and values encompass not just things like 5 or "Hello World!", but also functions. When an expression is evaluated in Haskell, the variables' values are looked up in the nearest defining scope. So in this example, + is redefined, in the scope of this expression only, to a function that produces 5 when both arguments are 2. – Luis Casillas – 2014-06-02T03:57:47.273

4I don't see why this gets so many votes. It doesn't make it appear that adding 2 + 2 gives the answer 5 at all. It's too explicit - big bzzzzzt! – GreenAsJade – 2014-06-04T13:10:46.550

It is rather too explicit. Better would be to redefine it in one place, and have the call in another, further down the stack. It isn't possible to compile a Haskell program with a modified version of the Haskell prelude, is it? – David Conrad – 2014-06-04T21:46:44.077

@JanDvorak Damn it, I always get that part wrong. – Ming-Tang – 2014-07-03T16:13:39.740

294

C

Pretty cheap trick but I'm sure I will trap the most of you.

int main() {
    int a = 2 + 2;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     a++;
    printf("%d",a);
    return 0;
}

Try it here

Scroll the code to the right.
I'm not sure on Windows/Linux but on OSX, the scrollbar is not visible.
Anyway, this is a good reason to enable "space visualization" on your favorite code editor.

Michael M.

Posted 2014-05-30T06:54:35.963

Reputation: 12 173

1

That got me ahahaha! Check out my C answer, love seeing C used on CodeGolf :D http://codegolf.stackexchange.com/a/59591/16513

– Albert Renshaw – 2015-10-04T03:52:44.593

You got me. This trick will be much fun if someone designs an editor that allows colouring the letters and setting a camera on programmers while they debug the code. – CroCo – 2016-01-04T10:42:32.097

When you click "Run it here" and then "Run" it wordwraps. – NoOneIsHere – 2016-03-11T17:19:14.463

96Scrollbar is visible in Chromium, but who pays attention to it at first? :) – Ruslan – 2014-05-31T17:56:51.173

172To confuse folks, you might add a comment line that is long enough to "explain" the existence of a scrollbar, but dull enough so that noone cares to (scroll in order to) read it. – Hagen von Eitzen – 2014-05-31T22:29:20.843

2Well, I had spotted the scrollbar (in Firefox). – johnchen902 – 2014-06-01T09:58:34.317

22In OS X, scrollbar visibility by default depends on whether a mouse is connected. If there's just a touchpad, scrollbars are overlaid and fade out when not in use. If there's a mouse connected, scrollbars steal space from the context box and are always visible. You can test this by unplugging and plugging in a USB mouse to a MacBook. This can be configured in System Preferences, of course. – Andrea – 2014-06-01T12:15:27.143

49Clever, but on mobile it just wordwraps :) – Logan – 2014-06-01T18:42:28.550

31This is the only time that scrolling SE code windows don't make me want to break someone's fingers. – ObscureRobot – 2014-06-01T21:23:11.247

3Rather than space-visualization, get an IDE which properly formats code. That will fix not just this problem, but a host of others. – BlueRaja - Danny Pflughoeft – 2014-06-02T22:30:32.357

1You. are. evil. Great answer. – jpmc26 – 2014-06-04T05:36:42.000

2This is how i passed my remake 'malloc' assignment – marabutt – 2014-06-06T03:40:16.453

1@Ruslan Me? Now that is evil. – Anonymous Pi – 2014-06-06T16:15:33.480

1@AnonymousPi you must have intended to address not me... – Ruslan – 2014-06-06T19:08:41.617

1@Ruslan No, I meant that I noticed the scrollbar and that Michael's post was evil because it seems that few people noticed it... – Anonymous Pi – 2014-06-07T20:07:06.137

@Logan not for me in the Stack Exchange Android app (Nexus 5). – nyuszika7h – 2014-07-02T08:28:58.280

184

GolfScript

4:echo(2+2);

Prints 5.

Of course GolfScript has a syntax that is markedly different from other languages, this program just happen to look like something Basic or C-ish.

4   - Put the number 4 on the stack. Stack content: 4
:echo - Save the value at the top of the stack to the variable echo. Stack content: 4
(   - Decrement the value at the top of the stack by 1. Stack content: 3
2   - Put the number 2 on top of the stack. Stack content: 3 2
+   - Add the two numbers on top of the stack. Stack content: 5
2   - Put the number 2 on top of the stack. Stack content: 5 2
)   - Increment the value at the top of the stack by 1. Stack content: 5 3
;   - Remove the top element from the stack. Stack content: 5

GolfScript will by default print anything left on the stack after execution has finished.

aaaaaaaaaaaa

Posted 2014-05-30T06:54:35.963

Reputation: 4 365

9i like it becaus it doesn't seem like it's tricking you with math or semantics, it seems so straightforward and yet 5 ^^ – dwana – 2014-12-26T10:44:54.107

Maybe using print will catch more programmers. Then again, most programmers know echo! – wizzwizz4 – 2016-03-11T18:40:35.180

3Can you explain that for people who don't speak GolfScript please? – MadTux – 2014-06-10T09:42:28.400

1@MadTux Here you go. – aaaaaaaaaaaa – 2014-06-10T16:14:03.997

1Thanks. (I'll upvote later because I reached my daily limit, here's a beer.) – MadTux – 2014-06-10T16:21:50.647

5Simple and cheaty, I love it. +1 – seequ – 2014-06-10T16:22:01.677

145

Java

Always have to round your doubles, folks

public class TwoPlusTwo {
  public static void main(String... args) {
    double two = two();
    System.out.format("Variable two = %.15f%n", two);
    double four = Math.ceil(two + two); // round just in case
    System.out.format("two + two = %.15f%n", four);
  }

  // 20 * .1 = 2
  private static double two() {
    double two = 0;
    for(int i = 0; i < 20; i++) {
      two += .1;
    }
    return two;
  }
}

Output:

Variable two = 2.000000000000000
two + two = 5.000000000000000

Explanation:

No, seriously, you always have to round your doubles. 15 isn't enough digits to show that the two() method actually produces 2.0000000000000004 (16 is enough, though).

In the raw Hex representations of the numbers, it's only a 1 bit difference (between 4000000000000001 and 4000000000000000)... which is enough to make the Math.ceil method return 5, not 4.

durron597

Posted 2014-05-30T06:54:35.963

Reputation: 4 692

@JannisFroese this is now my favourite comment on this SE – Cruncher – 2016-01-05T16:56:29.550

61Math.ceil(two + two); // round just in case I see what you did there – Tim S. – 2014-05-30T16:59:02.237

17Making both a function and a variable with the same name... Wow. – configurator – 2014-06-01T17:30:23.733

If you chose a small enough increment, could you get your two() up to 2.5? – Ben Jackson – 2014-06-01T20:57:25.170

@BenJackson if I did, the function two() wouldn't return 2 anymore. – durron597 – 2014-06-01T22:51:27.083

107@configurator that's nothing, there isn't even a class named two. Production grade java is Two two = Two.two.two(); with Two.two being of type TwoFactory. – Jannis Froese – 2014-06-02T01:09:21.610

36Two.Infinity.And.Beyond() – CincauHangus – 2014-06-02T10:00:10.610

Ugh, too many twos to count! – Rob – 2014-06-02T15:27:42.450

4@Caleb oh please all languages have issues with double rounding – durron597 – 2014-06-04T12:10:48.020

@durron597: Not "all". Perl 6 for example doesn't have problems with this example.

– Konrad Borowski – 2014-06-05T11:37:23.430

Why is two = 2.0000000000000004? As far as I see it, two = .1 * 20, so where does the 0.0000000000000004 come from? – ACarter – 2014-06-05T19:01:27.123

3@ACarter Thats because 0.1 can't be represented exactly in the double datatype. – Ral Zarek – 2014-06-06T09:52:15.153

@RalZarek you mean 1/10 can't be represented exactly? o_O – nyuszika7h – 2014-07-02T08:34:04.930

2@nyuszika7h doubles are stored in base 2 internally. This means that only fractions where the denominator is a power of 2 have a finite number of "decimals". 1/10 for example is .001100110011... in base 2. – Ral Zarek – 2014-07-02T11:26:21.917

@RalZarek that's interesting, I didn't know. – nyuszika7h – 2014-07-02T13:15:58.387

7@TimS I ceil what you did there – thenaglecode – 2014-07-11T04:10:58.347

135

BBC BASIC

EDIT: For Andrea Faulds and Squeamish Ossifrage, a more convincing version using a different interpreter: http://sourceforge.net/projects/napoleonbrandy/

  MODE 6
  VDU 23,52,254,192,252,6,6,198,124,0
  PRINT
  PRINT "2+2=";2+2
  PRINT "2+3=";2+3

enter image description here

This actually prints the number 4, but the VDU 23 redefines the font for ASCII 52 so that it looks like a 5 instead of a 4. Screen mode 6 was selected for aesthetic reasons (characters of a reasonable size.)

The original image using the emulator at http://bbcbasic.co.uk/bbcwin/bbcwin.html. (with slightly different code) can be seen in the edit history.

Level River St

Posted 2014-05-30T06:54:35.963

Reputation: 22 049

This trick would also work on the Amstrad CPC (464, 6128, etc.), however, if you try to copy the character back into memory (e.g. with the copy cursor) it will read both 4 (which now looks like 5) & 5 as 4, because it tries to match the pattern of pixels to a character and 4 comes before 5! – CJ Dennis – 2016-02-04T05:13:51.620

8Those fonts look different though. Do you think you could make it use the correct font? – Andrea – 2014-06-01T12:18:46.057

@AndreaFaulds I'm using the emulator from http://www.bbcbasic.co.uk/bbcwin/bbcwin.html. It supports the font redefinition of original BBC Basic on an 8x8 grid. But the default font of the emulator is clearly higher res than 8x8. So I could probably do a better job, but it wouldn't be perfect. I suppose I could redefine the font for all 5 as well as 4, then they would look the same.

– Level River St – 2014-06-01T18:05:00.397

5@AndreaFaulds The question didn't say that the result should be indistinguishable from other 5s. I think this is actually a feature. 2+3=5 and 2+2=5' – Ben Jackson – 2014-06-01T20:55:23.110

1This matches the original font in the BBC Micro: VDU 23,52,126,96,124,6,6,102,60,0 – r3mainer – 2014-06-02T10:37:38.700

@squeamishossifrage thanks for the info. It won't match the font in the emulator though. Your example is 7 pixels high, just like mine. Also it has a zero at the bottom, just like mine, whereas it looks like I need to move it down a bit (i.e, have the zero at the top instead of the bottom.) A key difference is that I have 126,64 whereas you have 126,96, and you have some 6's instead of my 2's. That's because the original BBC font had thick vertical lines, so it could be read easily in 80 column format on a standard TV screen. – Level River St – 2014-06-02T10:46:26.320

@squeamishossifrage I tried another interpreter, which uses a similar (but not identical) 8x8 font and got much more convincing results. Your original font does look 100% authentic though. – Level River St – 2014-06-02T19:51:44.027

@BenJackson and I didn't think it did, but it would be so much nicer if it looked the same :( – Andrea – 2014-06-05T01:30:46.837

@AndreaFaulds Take a look at the answer now. I fixed this a couple of days ago by using Brandybasic instead of BBCwin. The one I used before is a much better emulator in general, but in this case the fact that Brandybasic uses an 8x8 font made it possible to copy the font exactly. – Level River St – 2014-06-05T20:41:45.413

@steveverrill Aha, awesome :) – Andrea – 2014-06-14T00:50:17.417

134

Brainfuck

+++++           +++++
    +               +    
    +     +         +     +++++
+++++    +++    +++++     
+         +     +         +++++
+               +
+++++           +++++.

Output:

5

Try it here.

I know this might sound a little to simple, but I tried to be creative, as suggested in original post.

tigrou

Posted 2014-05-30T06:54:35.963

Reputation: 2 349

1I don't understaaaand – Leif Willerts – 2015-10-29T21:54:56.403

1I don't know brainfuck, it took me a couple of minutes to figure this out. ASCII 53, right? – Level River St – 2014-06-05T21:12:43.520

4As long you have the +++++. you can paint anything. – Eduard Florinescu – 2014-06-06T10:20:37.557

1@steveverrill : yes you are right. (and this is the only way to output ascii characters in BF). – tigrou – 2014-06-06T11:32:08.157

105

Bash

Since this is a , I guess I should use a long-winded method...

For people who don't know Bash: $((...expr...)) is a syntax to evaluate arithmetic expressions. $(bc<<<...expr...) does the same using the bc command-line calculator.

v=2                     #v is 2
v+=2                    #v is 4
v=$(($v*5))             #v is 20
v=$(($v-16))            #v is 4
v=$(bc<<<"sqrt($v)+2")  #v is 4 (sqrt(4) is 2)
v=$(bc<<<"$v/4+3")      #v is 4 (4/4 = 1)
echo '2+2=' $v          #So v is 4...?

Output

2+2= 5

Explanation

The second line concatenates v and 2 instead of adding them, to make 22.
Actual explanation:
v=2 #v is 2 v+=2 #v is 22 v=$(($v*5)) #v is 110 v=$(($v-16)) #v is 94 v=$(bc<<<"sqrt($v)+2") #v is 11 (by default, bc rounds to integers) v=$(bc<<<"$v/4+3") #v is 5 (11/4 is 2 with rounding) echo '2+2=' $v #TADAAAM

user16402

Posted 2014-05-30T06:54:35.963

Reputation:

8Nice maths trick going on there! – tomsmeding – 2014-05-31T19:07:38.080

5@tomsmeding It was quite fun, although about halfway through I realised that I had put 15 instead of 16 in line 4. Luckily, it still worked because of bc's rounding – None – 2014-06-01T16:28:45.273

1Oh this is just fabulous. lmao – Joe Harper – 2014-06-03T10:00:23.083

2See if you like the look of this style which is also valid Bash (eliminates the dollar signs, allows spaces around the equal sign and allows combined assignment operators): ((v = v * 5)) or ((v *= 5)) – Paused until further notice. – 2014-06-09T21:29:06.430

2Nice one, but I spotted the += thing immediately. – nyuszika7h – 2014-07-02T08:41:55.850

@nyuszika7h It's probably easy to spot if you're very familiar with Bash. But users of other languages will expect Bash to handle 2 as an integer. – None – 2014-07-03T19:54:54.533

i don't understand how this meets the requirements. there isn't a single addition expression of the form "2+2" anywhere in the code. the only underhanded aspect of this code is the misleading comments. you could have read the value "A=2.5" from a file, added a false comment that says it has the value "A=2", and then printed the result of "A+A" – ardnew – 2014-07-24T04:07:42.233

2@ardnew yes there is. the first two lines (v=2 and v+=2): to someone unfamiliar with Bash variable handling, that would be equivalent to 2+2, but it is in fact "2"+"2", i.e. "22". the other comments in the code are only wrong because of this. I know, not everyone finds this funny – None – 2014-07-24T07:11:17.047

101

Python

Inspired by the Java answer:

>>> patch = '\x312\x2D7'
>>> import ctypes;ctypes.c_int8.from_address(id(len(patch))+8).value=eval(patch)
>>> 2 + 2
5

Like Java, CPython uses the same memory location for any copy of the first few small integers (0-255 if memory serves). This goes in and directly edits that memory location via ctypes. patch is just an obfuscated "12-7", a string with len 4, which eval's to 5.

A more obfuscated version

exec("\x66\x72\x6f\x6d\x20c\x74\x79\x70e\x73\x20\x69\x6d\x70\
\x6f\x72\x74\x20c\x5f\x69\x6e\x748\x20a\x73\x20x\x3bf\x72\x6f\
\x6d\x20\x73\x74\x72\x75c\x74\x20\x69\x6d\x70\x6f\x72\x74\x20\
ca\x6cc\x73\x69\x7ae\x20a\x73\x20x0\x3bx\x2ef\x72\x6f\x6d\x5f\
a\x64\x64\x72e\x73\x73\x28\x69\x64\x284\x29\x2bx0\x28\x27\x50\
\x50\x27\x29\x29\x2e\x76a\x6c\x75e\x3d5")

Beyond 2+2

As OP mentioned, 2+2 can be kinda boring; so here's some cleaner, multiplatform, multi-width code for wanton abuse.

from __future__ import division, print_function
import struct
import ctypes
import random

# Py 2.7 PyIntObject:
# - PyObject_HEAD
#     - PyObject_HEAD_EXTRA [usually nothing unless compiled with DEBUG]
#     - (Py_ssize_t) ob_refcnt
#     - (_typeobject) *ob_type
# - (long) ob_ival

# two platform-sized (32/64-bit) ints (ob_refcnt and *ob_type from above)
offset = struct.calcsize('PP')

num = 60
nums = list(range(num))
addresses = [id(x) + offset for x in nums]
random.shuffle(nums)

for a, n in zip(addresses, nums):
    ctypes.c_ssize_t.from_address(a).value = n

print('2 + 2 =', 2+2)
print('9 - 4 =', 9-4)
print('5 * 6 =', 5*6)
print('1 / 0 =\n', 1/0)
print('(1 + 2) + 3 = ', (1+2)+3)
print('1 + (2 + 3) = ', 1+(2+3))
print('(2 + 3) + 1 = ', (2+3)+1)
print('2 + (3 + 1) = ', 2+(3+1))

Running with Python 2.7...ignore that line at the end. Works in Windows 64-bit and Ubuntu 32-bit, the two systems I have easy access to.

$ python awful.py 
2 + 2 = 24
9 - 4 = 49
5 * 6 = 55
1 / 0 = 0.76

(1 + 2) + 3 =  50
1 + (2 + 3) =  68
(2 + 3) + 1 =  50
2 + (3 + 1) =  61
Segmentation fault (core dumped)

Unsurprisingly, we can break the associative property of addition, where (a + b) + c = a + (b + c), as seen in the 1st and 2nd 1+2+3 lines, but inexplicably we also break the commutative property (where a + b = b + a; 2nd and 3rd lines). I wonder if the Python interpreter just ignores superfluous parentheses around addition expressions.

Nick T

Posted 2014-05-30T06:54:35.963

Reputation: 3 197

eek... don't try the 1/0 one – ev3commander – 2015-10-29T22:12:39.593

96Yes, we definitely all just casually ignore segfaults... – None – 2014-05-31T11:20:38.250

10It's worth mentioning that this isn't really a Python trick and is only specific to the C implementation of Python. – xApple – 2014-06-02T00:05:05.193

Python 2.7.6, windows, 64-bit did not work with from_address(id(4)+8)). I changed this to from_address(id(4)+16)) and it worked fine. Are you sure your windows 64-bit installation is 64-bit python, or is it 32-bit python running in 64-bit windows? – DavidJFelix – 2014-06-02T19:01:00.930

@DavidJFelix I fully know that the short example at the top doesn't work in x64 without a correction like you make. That's why I mention my subsequent code being "multi-width", wherein it uses struct.calcsize('PP') to come up with the offset – Nick T – 2014-06-02T19:08:10.437

1@NickT Ah! okay. I was under the impression that you had tried the original under the same 64-bit windows, 32-bit ubuntu setup – DavidJFelix – 2014-06-02T19:12:14.870

22exec('\x66\x72\x6f\x6d\x20\x63\x74\x79\ \x70\x65\x73\x20\x69\x6d\x70\x6f\ \x72\x74\x20\x63\x5f\x69\x6e\x74\ \x38\x3b\x20\x69\x6d\x70\x6f\x72\ \x74\x20\x73\x74\x72\x75\x63\x74\ \x3b\x20\x63\x5f\x69\x6e\x74\x38\ \x2e\x66\x72\x6f\x6d\x5f\x61\x64\ \x64\x72\x65\x73\x73\x28\x69\x64\ \x28\x34\x29\x20\x2b\x20\x73\x74\ \x72\x75\x63\x74\x2e\x63\x61\x6c\ \x63\x73\x69\x7a\x65\x28\x27\x50\ \x50\x27\x29\x29\x2e\x76\x61\x6c\ \x75\x65\x3d\x35') Is a modified first version. I made this so I could drop it into $PYTHONSTARTUP in /etc/profile as red team in hacking competitions. – DavidJFelix – 2014-06-02T20:14:36.080

@DavidJFelix that's awful :P – Nick T – 2014-06-02T20:51:45.807

1@NickT It's not the most underhanded thing I've done for red team tactics. I actually think you could probably break 3/5 python scripts if you changed the value of 1 to 0. – DavidJFelix – 2014-06-02T22:00:12.483

Something is messed up with my paste... I don't think it handled my code correctly above. – DavidJFelix – 2014-06-02T22:16:49.510

@DavidJFelix it probably converted newlines into spaces, so then your backslashes don't mean anything – Nick T – 2014-06-02T22:26:14.447

2

Yeah. Sidenote, it seems that 1, 0 and -1 are some of the numbers that python immediately segfaults with. I was thinking those would be the worst for screwing up python programs behavior. It may be possible to utilize fuckitpy to contain these errors.

– DavidJFelix – 2014-06-02T23:21:44.943

1@professorfish I wanted to upvote your comment, but I don't want to change the number of 42 votes :P – MadTux – 2014-06-10T09:30:33.297

@DavidJFelix: I don't think fuckitpy contains segfaults. It would be rather impressive if it did. (I can think of one way: trap the segfault, longjmp out of the broken stack frame, and resume execution at the next bytecode...but this will probably cause a ridiculous amount of breakage) – nneonneo – 2014-07-14T15:32:39.880

1FYI, for anyone looking to continue being a jerk in python3, Python 3 uses longs now. In python3 64 bit, the byte offset seems to be "24" or calcsize('PPP'). I haven't tested this in 32bit yet. – DavidJFelix – 2014-07-24T19:15:01.133

86

JavaScript:

g = function () {
  H = 3
  return H + H
}

f = function () {
  Η = 2
  return Η + H
}

// 3 + 3 = 6
alert(g())
// 2 + 2 = 5
alert(f())

Check it at http://jsfiddle.net/qhRJY/

Both H (Latin letter capital h) and Η (Greek letter capital eta) are set to the global scope because they were not defined as local to the functions with the var keyword. While they look similar, they are actually 2 different variables with 2 different values. Using Ctrl+F in your browser you will find that Η (eta) shows up significantly less than H (h) on this page.

Konstantin Weitz

Posted 2014-05-30T06:54:35.963

Reputation: 1 083

Haha, on mobile it's grey and very obvious – Universal Electricity – 2015-11-07T08:58:27.457

You can also mess with the alert() and/or console.log() functions themselves. For instance: https://jsfiddle.net/uk1v0mv0/2/

– aroth – 2015-12-21T05:38:20.167

can you explain this please? – Sam Creamer – 2014-05-31T02:18:11.727

4

@Sam even though the two 'H's look the same, they are in fact 2 entirely different characters. In Unicode there can be different characters that look the same but have different code-points. In this specific case; the other "H" is actually the greek letter Eta.

– d3dave – 2014-05-31T08:39:45.913

79

Using homoglyphs to "confuse" readers is now officially not funny.

– John Dvorak – 2014-06-01T05:46:13.593

29The homoglyphs become funny in combination with javascript's ridiculous global variables. – Konstantin Weitz – 2014-06-01T17:16:54.377

2This is not 2+2=5, it is 2+2'=5 note the ref on the 2nd 2. not the same – Funkodebat – 2014-06-01T21:10:16.990

smart! I liked it. – Felipe – 2014-06-02T04:13:18.697

@Funkodebat what do you mean by that? – Konstantin Weitz – 2014-06-02T04:28:29.797

3It's not the "Unicode Η character", it's Latin H and Greek Eta (Η). – treat your mods well – 2014-06-02T15:39:15.793

1On my screen it might as well be saying 2+3=5, which doesn't seem underhanded at all. That's exactly what I would expect. – Shaz – 2014-06-02T16:43:22.437

I didn't realize that if you don't use the var keyword, the variable is global. interesting – Sam Creamer – 2014-06-02T17:40:43.493

@KonstantinWeitz he's not doing h + h, because in the example, one of the h's is not h, its like doing a + b. one of the h's isn't 2. its like saying 2 + (not really 2) = 5 – Funkodebat – 2014-06-02T18:58:49.390

3@JanDvorak The problem with "officially" is that only 27 people at this time have agreed to make it official. Posting in that thread does not make it authoritatively not funny. – Vortico – 2014-06-04T13:30:05.773

4@Vortico hmm... what do you wish when a FAQ question doesn't suffice? A FAQ question linked from the help center? Note that only moderators can apply the [meta-tag:faq] tag. As for the answer - the question states "score +5 or more and at least twice as many upvotes as downvotes". The answer has 27 upvotes and no downvote. That sounds to me like fulfilling the criteria stated in the answer, and the amount of upvotes is pretty impressive for the second oldest answer on a question on the meta site of a site where only 124 people have voted more than 10 times. How many would you like? Everyone? – John Dvorak – 2014-06-04T13:47:58.570

1@JanDvorak If those who agree would downvote this question, there would be no need for a meta question like that. The community will eventually grow sick of this kind of humor and no longer upvote these answers, so there is no need for a remark to remind people that humor is objective. – Vortico – 2014-06-04T14:50:28.997

@Vortico well, I did downvote. I am genuinely surprised by the amount of upvotes this has got. Reddit? – John Dvorak – 2014-06-04T14:56:59.203

Just not funny as the C(From Michael) example. – DontVoteMeDown – 2014-06-04T20:08:31.500

@Funkodebat: By that same logic the C example is not doing 2+2=5, but rather 2+2+1=5 and wouldn't be special either. – David Mulder – 2014-06-07T16:42:51.443

72

JavaScript

function addDecibels(){return (10*Math.log10([].reduce.call(arguments,(p,c)=>p+Math.pow(10,c/10),0))).toFixed(1);}

alert( addDecibels(2,2) );

The underhanded bit is that its not actually underhanded - if you add a 2dB sound source to another 2dB sound source then resulting combined noise will be 5dB (and if you add two 30dB sources then its 33dB) as they are measured on a log scale.

You can see it on a different calculator here.

MT0

Posted 2014-05-30T06:54:35.963

Reputation: 3 373

Well it's actually more like 5.01 decibels, but far away enough from 4 to count. – Joe Z. – 2016-01-12T20:57:53.790

68

PHP

echo '2 + 2 = ' . (2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'dunno');

Which produces:

2 + 2 = 5

This is because in PHP, ternaries are calculated left to right, so it's actually
(2 + 2 === 4 ? 4 : 2 + 2 === 5) // 2 + 2 is == 4, and 4 == true, therefore echo 5 ? 5 : 'dunno';

MrLore

Posted 2014-05-30T06:54:35.963

Reputation: 839

35

obligatory phpsadness

– wchargin – 2014-06-01T04:12:48.017

1I've got another PHP example: $a=2;echo "2+2=".$a++ + $a++; – avall – 2014-06-01T21:27:21.247

It's obvious that $a++ makes 3 and the result will be 6. I don't get what you're thinking. – Ozh – 2014-06-02T09:58:16.070

excellent point :D – Alireza Fallah – 2014-06-02T12:19:58.877

@WChargin: Why is right-associativity more correct? – Janus Troelsen – 2014-06-02T14:33:47.223

1

@Janus PHPsadness #30 explains it well

– wchargin – 2014-06-03T04:13:49.480

@Ozh You're wrong. $a++ returns $a and AFTER returning $a it increments it by one. It's the rule which is used by a lot of languages having ++ operator. Also, RTFM: http://www.php.net/manual/en/language.operators.increment.php

– avall – 2014-06-03T10:39:37.343

2Also trending on stackexchange... – recursion.ninja – 2014-06-04T15:26:09.373

66

JavaScript

var total = 2 + 2;

if(total = 5)
{
    alert('I guess 2 + 2 = 5');
}
else
{
    alert('The universe is sane, 2 + 2 = 4');
}

user1886419

Posted 2014-05-30T06:54:35.963

Reputation: 1 015

I find it very obvious – Oliver Ni – 2015-01-01T23:14:59.683

Ah, javascript and its strange features. – Bálint – 2016-03-02T17:58:42.233

73= instead of ==, easy to see and frankly rather uninspired. – ApproachingDarknessFish – 2014-05-30T20:06:57.173

19Have an upvote anyway, I make that mistake a lot – None – 2014-05-31T10:51:43.797

6I still like this answer – Sam Creamer – 2014-06-02T17:43:11.230

5I like it too. Not every language uses = only as an assigment but a comparison operator (e.g. Pascal, SQL, VB) – avall – 2014-06-02T20:27:54.853

57

C#

    static void Main(string[] args)
    {
        var x = 2;
        var y = 2;

        if (1 == 0) ;
        {
            ++x;
        }

        Console.WriteLine(x + y);
    }

Grax32

Posted 2014-05-30T06:54:35.963

Reputation: 1 282

7ah, the good old trick with rogue characters. That's why you should use 1TBS everywhere. – John Dvorak – 2014-05-30T17:52:04.013

11@JanDvorak Does this work because of the semicolon after the if statement? I don't know C# but I have used C++ – None – 2014-05-30T18:31:51.020

5@professorfish that's what I assume. Also, languages that don't let you insert random curly braces FTW. – John Dvorak – 2014-05-30T18:33:04.443

12Without the ";", the if statement controls whether the code block will be executed. With the ";" in there, the if is evaluated but nothing is done with the result. Then the code block is executed every time, regardless. In C#, it is perfectly acceptable to have random code blocks. – Grax32 – 2014-05-30T18:58:59.753

2I got myself with this one the other day. I had a for loop with a ; after it, which was perfectly intentional as I was using the empty loop to advance a cursor. I accidentally removed the semi-colon, everything blew up, and I couldn't figure out why. – mpen – 2014-06-02T00:32:43.737

56

It's dangerous to decorate your Javascript with ASCII art.

  -~// JS  \\~-
 ~-// Maths \\-~
-~// Madness \\~-

     (2 + 2)

When the comments are removed, the remaining symbols and operators evaluate to
-~~--~(2 + 2) This makes use of the Bitwise Not operator (~) in JS, along with a handful of Minus signs which will negate the values along the way.

Dan Prince

Posted 2014-05-30T06:54:35.963

Reputation: 1 467

3I was wondering how the -- operator was acceptable as it should error out with Invalid left-hand side expression in prefix operation; however I realized that there is a whitespace character between them. – usandfriends – 2015-04-09T01:51:09.753

53

Bash

#!/bin/bash

# strings of length 2
x="ab"
y="cd"

# add lengths by concatenation
c="$(cat<<<$x; cat<<<$y)"

# display the lengths of the parts and the sum
echo "${#x} + ${#y} = ${#c}"

Output:

2 + 2 = 5

The output from each cat will have an implicit newline, but the final newline is stripped off by the command substitution $( )


Here's another:

#!/bin/bash

# Create an array of ascending integers
a=({1..10})

# Use the sum to index into the array
s="2 + 2"
i=$(($s))
echo "$s = ${a[$i]}"

Bash arrays are zero indexed

Digital Trauma

Posted 2014-05-30T06:54:35.963

Reputation: 64 644

R is 1-indexed. – Hauleth – 2014-12-26T07:50:23.843

Mathematica is 1-indexed. – LegionMammal978 – 2015-04-09T23:40:21.917

I would have never caught the first one... – Isiah Meadows – 2014-05-30T18:26:30.460

3I did actually catch the first one, as I've had lots of problems with things like that when golfing in Bash. As for the second one, where aren't arrays zero-indexed? – None – 2014-05-30T18:29:52.653

3@professorfish Applescript, for example: set a to {1, 2, 3, 4, 5, 6, 7, 8} item 4 of a – Digital Trauma – 2014-05-30T18:32:42.157

12@DigitalTrauma Applescript is weird – None – 2014-05-30T18:44:32.247

5zsh uses 1-indexed arrays (and $arr[0] is simply unset or undefined or something), unless the KSH_ARRAYS option is set, in which case arrays are 0-indexed. – chepner – 2014-05-30T18:57:32.543

@chepner Wow thats cool - If I run the indexing script under zsh, then it yields "2 + 2 = 4"! Thats a big shell portability gotcha I didn't know about – Digital Trauma – 2014-05-30T19:00:53.947

4@professorfush: Lua & Fortran are 1 indexed. Anytime I count to 10, I always start at 1, not 0. :D – Kyle Kanos – 2014-05-30T23:23:28.700

1@professorfish Matlab matrices are 1-indexed. T__T – beerbajay – 2014-06-01T12:42:26.547

1@professorfish Pascal Strings are 1 indexed (for shortstrings, position 0 contains the length, for longstrings it's 0). – Jannis Froese – 2014-06-02T01:17:43.563

1@professorfish: AWK is 1-indexed. Perl can be 42-indexed (if $[ is equal to 42). fish shell is 1-indexed. Practically everything made before C is 1-indexed as well. – Konrad Borowski – 2014-06-04T16:16:56.147

49

Perl

# Generic includes
use strict;
use warnings;
use 5.010;
use Acme::NewMath;

# Ok, time to begin the real program.
if (2 + 2 == 5) {
    say 5;
}
else {
    say "Dunno...";
}

It depends on CPAN module called Acme::NewMath. Because of wrong file names in the module, this will only work on case insensitive file systems (like on Windows or Mac OS X), but I blame the original module's author here. Acme::NewMath implements mathematics according to the Ingsoc ideology.

Konrad Borowski

Posted 2014-05-30T06:54:35.963

Reputation: 11 185

16This is quite sly. Nobody ever looks at your imports/includes. – None – 2014-05-31T13:51:05.350

44

R

# add the mean of [1,3] to the mean of [4,0] (2 + 2)
mean(1,3) + mean(4,0)

output:

5

the code actually adds the mean of [1] to the mean of [4]. The correct way to use the mean function in R would be: mean(c(1,3)) + mean(c(4,0)) This is unlike some other mathematical functions in R, such as sum, max, and min; where sum(1,3), max(1,3), and min(3,1) would all give the expected answer.

ping

Posted 2014-05-30T06:54:35.963

Reputation: 590

7Not bad, fooled me for a bit. – qwr – 2014-06-02T06:22:50.580

37

Java

public class Five {
    public static void main(final String... args) {
        System.out.println(256.0000000000002 + 256.0000000000002);
    }
}

output:

512.0000000000005

Probably works in any language that uses the same kind of doubles.

aditsu quit because SE is EVIL

Posted 2014-05-30T06:54:35.963

Reputation: 22 326

7That's a very strange main signature. – Bertie Wheen – 2014-06-01T22:11:41.890

10Java implements variadic arguments as arrays under the hood. – CodaFi – 2014-06-02T04:47:48.967

4Took me a moment to realize that you are probably talking about the last digits in the doubles. I saw that the first digits added correctly (_2_56 + _2_56 = _5_12), but it seems more likely that you mean 256.000000000000_2_ + 256.000000000000_2_ = 512.000000000000_5_ (note: underscores used to "bold" the digits. – Justin – 2014-06-09T06:59:55.997

35

Befunge

This is written in Befunge, but is designed to look like Python.

#>>>>>>>>>>>>>>>>>v
# Calculate 2 + 2 v
#>>>>>>>>>>>>>>>>>v
def add(v,w):
    return v+w
 # I rewrote this 5 times and it still doesn't work

print add(2,2) #... Still not working

# email: MarkSmith@example.com

When run (with the correct interpreter) the program will print 5.

Explanation:

A Befunge program is made up of a grid of single character commands. The first command is the one in the top left corner, and the reading of commands proceeds to the right. But the direction can change during program execution.

Only the first row of characters, and the column of characters starting with the v in the first row are run. The characters in question do:

# - skip the next command
> - From now on, commands are read to the right of the current command
v - From now on, commands are read below the current command
5 - Push 5 to the stack
. - Pop and print the number at the top of the stack
@ - End the program
<space> - Do nothing

If you knew you were programming in Befunge, this wouldn't really trick anyone. But if you came across this and didn't realize it was Befunge, it most likely would.

Matt

Posted 2014-05-30T06:54:35.963

Reputation: 1 395

11+1, This is very devious, because who the hell looks at the program that runs the source code when debugging? – MrLore – 2014-07-25T03:45:38.693

33

JavaScript

Code:

var a = 3;
а = 2;
a + а;

Output:

5

You can test it yourself on your console or check this Fiddle

William Barbosa

Posted 2014-05-30T06:54:35.963

Reputation: 3 269

3Clever... I always wanted to created an obfuscator that worked like this. – Brian Mortenson – 2014-05-30T22:21:17.323

6Can you point me to a resource or explain to me why this works. I know it does work because I checked out the Fiddle of it, but I don't understand why. – Family – 2014-05-30T23:14:19.190

I sense some sneaky unicode. – cardboard_box – 2014-05-31T01:42:22.070

29the "a" variable isnt the same both times (sorry if im spoiling this). Sneaky unicode indeed – Sam Creamer – 2014-05-31T02:16:07.160

There's always a bit of sneaky unicode... – None – 2014-05-31T09:51:02.313

6I love how the next character, U+0431, is б—almost 6! – wchargin – 2014-06-01T04:12:31.147

73

Using homoglyphs to "confuse" readers is now officially not funny.

– John Dvorak – 2014-06-01T05:56:11.590

40@JanDvorak That answer was posted after this one; it doesn't apply here. – Doorknob – 2014-06-01T12:26:53.397

@Jan — Unicode magic is my favourite trick ! – Nicolas Barbulesco – 2014-06-06T11:53:25.957

Where is the unicode? How can I see it? – Guillermo Gutiérrez – 2014-09-05T22:17:42.307

1Doing a quick search for a (Ctrl/Cmd + F) will reveal that the "a" on line 2 is not an 'a'. – geoff – 2014-09-15T08:59:08.333

30

C (Linux, gcc 4.7.3)

#include <stdio.h>

int main(void)
{
    int a=3, b=2;

    printf("%d + %d = %d", --a, b, a+b);  
}

It prints 2+2=5

So a=2, right?

gcc-4.7.3 evaluates the function parameters from right to left. When a+b is evaluated, a is still 3.

cpri

Posted 2014-05-30T06:54:35.963

Reputation: 727

16Nice use of unspecified behavior – chbaker0 – 2014-06-05T00:34:47.873

24

FORTRAN 77

       program BadSum
       integer i,a,j
       common i,a
       a = 1
       i = 2
       call addtwo(j) 
       print *,j
       end

       subroutine addtwo(j)
       integer a,i,j
       common a,i
c since a = 1 & i = 2, then 2 + 1 + 1 = 2 + 2 = 4
       j = i + a + a
       end

Standard abuse of common blocks: order matters; I swapped the order in the block in the subroutine so I'm really adding 1 + 2 + 2.

Kyle Kanos

Posted 2014-05-30T06:54:35.963

Reputation: 4 270

6@JanDvorak: Haha, I could have used FORTRAN IV in which I could redefine literals, e.g. 2=3 – Kyle Kanos – 2014-05-30T18:12:32.157

1@KyleKanos, that's what I thought this was going to be when I saw your post was written in FORTRAN. – danmcardle – 2014-05-30T21:56:28.720

@KyleKanos Do it! – ClickRick – 2014-06-01T03:10:40.353

1@KyleKanos: Did that work with integer literals or only floats? I would think that on a machine of that era, an integer literal and an address would have been the same size, but smaller than a float, so pooling float literals would save space but pooling int literals would not. – supercat – 2014-06-03T19:08:32.277

@supercat: I honestly don't know, it was quite literally before my time: FORTRAN IV was released in 1961 and superseded by FORTRAN 66 in 1966, I wasn't born until 1983. Even back then, as I understand it, it was a non-standard behavior that occurred with certain compilers. – Kyle Kanos – 2014-06-03T19:18:14.253

2@KyleKanos: My understanding is that compilers wouldn't allow a direct assignment to a literal, but function calls used pass by reference, and passing a floating-point literal to a function would generally pass the address of a value in a pool of floating-point literals. Passing an integer value to a function would cause it to be pooled, but most code that used integers would include the values directly. – supercat – 2014-06-03T19:23:11.790

@supercat: I'm honestly not sure. I do know that this "feature" of FORTRAN IV was obliterated in 1966 with the release of FORTRAN 66 (see Section 8.4 of that standard). – Kyle Kanos – 2014-06-03T19:45:02.123

Nice one. The literal redefinition was more an artifact of nonexistence of protected constant memory, than FORTRAN feature. Today the program will happily try something similar even in C, but will SIGSEGV when writing to read only memory. – Vladimir F – 2014-06-04T18:35:20.217

@supercat That's right. My first programming experiences were on an ICL 1900-series, with FORTRAN IV (so I remember abusing that very "feature" in my teens) and ALGOL 60 (the version with apostrophes around keywords). Ah, happy days! – ClickRick – 2014-06-05T22:26:48.310

24

Python

Code prints 5 which is correct answer for this task.

def int(a):
    return ~eval(a)

def add(a,b):
    return int(a)+int(b)

print ~add("2","2")

Edit: Here's alternative version which adds integers, not stringified twos.

def int(a): return ~eval(`a`)
def add(a,b): return int(a)+int(b)
print ~add(2,2)

Tilde is an unary inverse operator which returns -x-1, so first step is to get -6 and then with another operator in print function get 5

avall

Posted 2014-05-30T06:54:35.963

Reputation: 1 547

Why ~eval(\a`)instead of just~a`? – Andrea Corbellini – 2014-06-02T13:25:48.000

2I wanted to leave some of the int() functionality and eval() does the job if the input is a stringified integer :) – avall – 2014-06-02T14:27:32.460

24

Ruby

class Fixnum
    alias plus +

    def + (other)
        plus(other).succ
    end
end

puts 2 + 2

This increases the result of all additions whose first argument is a Fixnum (which 2 is, at least in MRI) by 1.

The side-effects of this are even worse than the Java version.

Lowjacker

Posted 2014-05-30T06:54:35.963

Reputation: 4 466

23

Ruby

Ruby has first class environments. This means lots of things. It also means that lots of things can be done that... maybe shouldn't.

def mal(&block)
    block.call
    for v in block.binding.eval("local_variables");
      block.binding.eval('if ' + v.to_s + ' == 4 then ' + v.to_s + ' = 5 end')
    end 
end

a = 2 + 2;
b = 2 + 4;
puts "2 + 2 = ", a
puts "2 + 4 = ", b

mal do
  puts "But in 1984..."
end

puts "2 + 2 = ", a
puts "2 + 4 = ", b

The output of this is:

2 + 2 = 
4
2 + 4 = 
6
But in 1984...
2 + 2 = 
5
2 + 4 = 
6

If you want to understand more about the joys and dangers of this, Ruby Conf 2011 Keeping Ruby Reasonable and read First-class environments from the Abstract Heresies blog.

user12166

Posted 2014-05-30T06:54:35.963

Reputation:

Also: class Fixnum; def +(n) 5 end end; 2 + 2 # => 5 – film42 – 2014-06-02T02:38:24.203

1To just do for the specific case: class Fixnum; alias_method :orig_plus, :+; protected :orig_plus; def +(n) self == 2 && n == 2 ? 5 : self.orig_plus(n) end end – Gary S. Weaver – 2014-06-05T03:26:39.520

21

Scheme

(define 2+2 5)
2+2 ;=> 5

Hauleth

Posted 2014-05-30T06:54:35.963

Reputation: 1 472

9hey! 2+2 isn't how you do addition in lisp! – John Dvorak – 2014-05-30T17:54:39.697

1So what? It seemingly add 2 to 2 as is in the task. – Hauleth – 2014-05-30T18:33:26.633

@JanDvorak Clearly, you're wrong then – Cole Johnson – 2014-05-31T03:16:10.023

119@JanDvorak I've never used lisp, but as I understand it it's something like ((((2))(()()))()()(()((((+))))()(((()(())((((2)))))()))(()))). – undergroundmonorail – 2014-05-31T04:00:47.023

2

"Redefining 2+2 as 5 is not very creative! Don't doublethink it, try something else." --- Well, in R5RS I can redefine + instead 2+2 or 2. The answer is here: http://pastebin.com/KHtm9Jmv

– Felipe – 2014-06-02T04:42:23.513

Mine: (define + (lambda (a b) (abs (-1+ (- (- a) b))))))

(+ 2 2) => 5 (+ 3 4) => 8 – Nick Russell – 2014-06-02T10:29:31.320

1@FelipeMicaroniLalli that adnotation was made after my answer so it doesn't count. – Hauleth – 2014-06-04T08:36:03.920

@Nick Russell, wth is -1+ ? :) I tried it on SISC and got this error: Error: undefined variable '|-1+|'. – Felipe – 2014-06-04T19:39:54.647

1@FelipeMicaroniLalli MIT-Scheme. (1+ x) => (+ x 1); (-1+ x) => (- x 1). You could replace mine with (define + (lambda (a b) (abs (- (- (- a) b) 1)))) – Nick Russell – 2014-06-05T12:04:37.553

Nice! But I prefer my solution because it is really confusing: (+ 1 2) => 3; (+ 2 3) => 5; (+ 2 2 2) => 6 ; (+ 2 2) => 5 – Felipe – 2014-06-05T20:32:49.657

20

C#

var c = Enumerable.Range(2, 2).Sum();

To someone not familiar, this will look like I'm getting a range starting and ending at 2. In reality, it starts at 2 and goes for two numbers. So 2 + 3 = 5.

Paul

Posted 2014-05-30T06:54:35.963

Reputation: 328

6A range starting and ending at 2 would be just { 2 }, wouldn't it? – Paŭlo Ebermann – 2014-05-31T22:12:49.867

1

@PaŭloEbermann Enumerable.Range doesn't take a start and an end, it takes a start and a count (of elements that will be enumerated).

– MasterMastic – 2014-06-01T00:21:03.767

14@MasterMastic I understood this from the explanation in the answer. But the "to someone not familar" meaning is supposed to be such a range (from the explanation in the answer), and my argument is that the expected result then would be 2, not 4. – Paŭlo Ebermann – 2014-06-01T00:29:13.133

1@PaŭloEbermann, yes that's one way to look at it also. I was thinking it might look more like I was supplying the numbers to add. So Enumerable.Range(1,2,3,4) would start at 1, end at 4, and would sum up to 10. – Paul – 2014-06-02T13:38:41.330

19

F#

Let's put in fsi following statement:

let ``2+2``= 5

Output:

val ( 2+2 ) : int = 5

Krzysztof Cieslak

Posted 2014-05-30T06:54:35.963

Reputation: 307

18

C

int main() {
        char __func_version__[] = "5";  // For source control
        char b[]="2", a=2;
        printf("%d + %s = %s\n", a, b, a+b);
        return 0;
}

The 5 is not too well hidden, I'm afraid. Doesn't work with optimization.

ugoren

Posted 2014-05-30T06:54:35.963

Reputation: 16 527

1Nice; I can't upvote if undefined behavior isn't allowed. – this – 2014-06-01T13:27:55.197

2@self., I don't see where relying on UB is banned. Many code golf answer rely on UB, and I think it's OK as long as it consistently happens on some reasonable platform. – ugoren – 2014-06-01T14:18:11.433

2I don't see where relying on UB is banned. I didn't find any rules on that either. It would be nice if that could be clarified. Many code golf answer rely on UB, and I think it's OK as long as it consistently happens on some reasonable platform Some specific rules on that would be nice. – this – 2014-06-01T19:27:07.217

17

Javascript

Here is another fun one. This time in Javascript

function Add(a,b) {
    return a + b;
}

alert(Add(2,2));

if (false) {
    function Add(a,b) { return ++a + b; }
    alert("This code is not to be executed!");
}

The 2nd function is still created and overwrites the first one, even though it is in the false code block. JavaScript creates all functions using the style "function Name" before other code.

Grax32

Posted 2014-05-30T06:54:35.963

Reputation: 1 282

11brb, I need to file a bug report... – primo – 2014-06-06T13:04:15.720

14

Perl

use strict;
use warnings;
sub sum { my $sum = 0; $sum += $_ for @_,0..$#_ ; $sum }
print sum( 2, 2 );

Explanation

Arrays are zero-indexed


And if that isn't underhanded enough:

use strict;
use warnings;

sub sum { my $sum = 0; while (@_ = each @_){ $sum += $_ for @_ } ; $sum }
print sum( 2, 2 );

Explanation

Seemingly innocuous assignment to @_ with each sums up the array indices along with the values.

Zaid

Posted 2014-05-30T06:54:35.963

Reputation: 1 015

The second program produces an infinite loop for me. See here

– Anant – 2014-06-07T13:15:50.493

@Anant : I know that Perl 5.18 updates the behaviour of each inside while conditionals. The above code works for versions 5.12 to 5.16

– Zaid – 2014-06-07T14:52:00.280

Ah okay, thanks! – Anant – 2014-06-07T15:45:01.577

11

C

I ended up writing two solutions. The first was designed to give correct output for all values other than 2+2 and be non-trivial to understand, even though it would be obviously suspicious. The second I'm more proud of, and is harder to see why the wrong answer is output.

First Solution

unsigned int add(unsigned int a,unsigned int b)
{
    return b+(a|(!~((a&1<<1)|(~(a&~(1<<1)))))&(!~(b&1<<1|~(b&~(1<<1)))));
}

This is a simple case of binary operations to check if a == b == 2, and incrementing a - without using any of those operators. Key things to look out for are that 1<<1 is 2, and that logical '!' implicitly casts to boolean, so gives you either 0 or 1 which can be added(using binary OR) to the 2+2 to get 5. Otherwise pretty straight forward, just hard to read.

Second Solution

#include <errno.h>

int main( void )
{
    char* buffer = (char*) malloc( 1024 );

    /// check the buffer allocated correctly before adding into it \\\
    if ( buffer )
    {
        sprintf( buffer,"addition example: 2+2=");  /// add the precursory line of intro text        \\\
        const int result = 2 + 2;                   /// calculate the hardcoded 2+2 sum              \\\
        sprintf( buffer, "%d", result );             
        printf( "%s", buffer );                     /// print out the finished statement to the user \\\
    }else{
        errno = EIO;                                /// EIO - input/output error, see <errno.h>      \\\
        printf("IO Error with error code:\n");
        printf( "%d", errno );
        return -1;
    }

    free( buffer );
    return 0;
}

Far more proud of this one. It pretends to be a simple example on "how to allocate and print to a buffer". Being so nice as to even provide error handling. There are a few different layers that add to it, but the key point is more than 50% of the lines are comments (from '\' escaping the new line in a previous comment). To get the 5, the errno is output with the value EIO, which is defined as 5 in the standard library. To see how it functions, using any good IDE will highlight most lines as comment and show the 4 lines that actually need to execute for it to work.

Bilkokuya

Posted 2014-05-30T06:54:35.963

Reputation: 241

11

piet

Simply pushes two 2's on the stack and adds them. Then outputs result.

It even has a helpfully drawn image of what it is doing.

For the colorblind like me, the tweaks are virtually undetectable.

piet

captncraig

Posted 2014-05-30T06:54:35.963

Reputation: 4 373

10

Python

Computers really use binary to add.

def in_binary(n):
    if n == 0:
        return [] # base case
    else:
        digit = n & 0x1 # bit mask
        return in_binary(n >> 1) + [digit] # recursion

def from_binary(b):
    # add value of each digit, using enumerate to get its place
    # list comprehensions are Pythonic
    return sum([(2**place) * value
                for place, value in enumerate(b)])

>>> two = in_binary(2)
>>> from_binary(two + two)
5

Try it.

This turns 2 into [0, 1], a reversed-order binary number, then instead of any real binary addition, concatenates the digits to form [0, 1, 0, 1], and then interprets that as a non-reversed-order binary number, which is 5.

Dan Getz

Posted 2014-05-30T06:54:35.963

Reputation: 533

Nice, two tricks hidden. – Paŭlo Ebermann – 2014-05-31T22:03:49.700

An explanation would be nice? – Jack Aidley – 2014-06-05T10:01:37.010

9

C++

#include <iostream>

class Int
{
public:
    Int(const int& a) : integ(a) {}

    friend std::ostream& operator<<(std::ostream& oss, const Int& rhs)
    {
        return oss << rhs.integ;
    }
    int operator+(Int o)
    {
        if(integ == 2 && o.integ == 2)
            return integ+o.integ+1;
        return integ+o.integ;
    }

private:
    int integ;
};

int main()
{
    Int two = 2;
    std::cout << two << " + " << two << " = " << two + two;
}

Output: 2 + 2 = 5

Try online!

NaCl

Posted 2014-05-30T06:54:35.963

Reputation: 528

1I wonder if C++14 could make this even better, with user-defined literals. – JDługosz – 2016-03-18T09:47:19.127

1Same answer I was going to post. Because operator overloading is evil in so many cases! :) – Mike McMahon – 2014-06-02T05:25:07.127

2And good in so many other! :D – NaCl – 2014-06-02T15:38:28.570

9

Commodore 64 Basic

1 POKE 2070, 51
2 PRINT 2+2

The Commodore Basic interpreter's sandboxing is, to put it mildly, non-existent. So why not engage in a bit of self-modifying code? Line 2, as written, is PRINT 2+2, but as executed, it's PRINT 3+2.

Mark

Posted 2014-05-30T06:54:35.963

Reputation: 2 099

I miss line numbers. – JDługosz – 2016-03-18T09:48:17.350

9

C

#define one 0.6+0.4
#define two one*2
#define zero one*two-two*one

int a = two+two+(zero*zero);
printf("%i",a);

Logs: 5


This one was a lot of fun!

Most humans will automatically put parens around variables. We've been taught to do this in math. x*5 is really (x)*5 because x could be something like 0.4+0.6 but you always simplify variables (in Math). But in compiler, CLANG just inserts it right in, no questions asked. So when I define one as 0.6+0.4 then define two as one*2 a human may see (0.6+0.4)*2 which = 2, but compiler sees 0.6+0.4*2, no parens, which will simplify to 0.6+0.8 which = 1.4

Really compiler reads my int a = as 0.6+0.4*2+0.6+0.4*2+(0.6+0.4*0.6+0.4*2-0.6+0.4*2*0.6+0.4) which is 4.75 --> (int)5.

Albert Renshaw

Posted 2014-05-30T06:54:35.963

Reputation: 2 955

7

Windows Command Script

set /a x = 1
set x = 0
:: this is essentially 0+2+2 right?!
set /a x += 2 + 2
echo %x%

It turns out that "set" with the /a flag ignores spaces before the = sign which normally would be part of the variable name. So "set /a x = 1" would change "x", but "set x = 0" would change "x " (note the space).

Robert Sørlie

Posted 2014-05-30T06:54:35.963

Reputation: 1 036

Hmm, using both variants in the same script makes it a bit suspicious. – Paŭlo Ebermann – 2014-05-31T22:04:55.457

At least to those of us who know cmd, that's not very underhanded. That code practically screams the answer ;-) – Joey – 2014-06-01T13:20:50.177

7

Javascript: (8 bytes)

2+2|!![]

Explanation:

(requested in comments)

This is due to implicit type conversion, ![] is false, !false becomes true , then true is implicitly converted to a number type (1) because on the left of the | operator is a number.

Another example:

2+2|!""

"" implicitly converts the empty string to false by ! then is negated by ! operator to true then to a number (1) because on the left of the | operator is a number.

Other variants using other operator and implicit type conversion might be:

2+2|!"" 
2+2|!0

or plain which is shortest (5 bytes)

2+2|1

but putting 1 in there makes is too obvious.

Eduard Florinescu

Posted 2014-05-30T06:54:35.963

Reputation: 1 863

7How is it "underhanded"? – nicael – 2014-06-02T19:11:07.860

@nicael added an explanation – Eduard Florinescu – 2014-06-03T04:35:51.210

7

Javascript

Use an array.

function add(a, b) {
    var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    return numbers[a + b];
}
alert(add(2, 2))

Will output

5

Javascript arrays will start from zero, but when I defined the array, I started with 1. Therefore, the result will actually be 1 more than it's supposed to be.

Potassium Ion

Posted 2014-05-30T06:54:35.963

Reputation: 191

7

Python

>>> import sys
>>> def dh(obj):
...     if isinstance(obj, int):
...         obj += 1
...     __builtins__._ = obj
...     print(repr(obj))
...
>>> sys.displayhook = dh
>>> 2 + 2
5

Adds 1 to any int-valued expression entered in the REPL.

dan04

Posted 2014-05-30T06:54:35.963

Reputation: 6 319

6

Perl 6

I have no idea why it happens. Help.

multi infix:<+>(2, 2) { 5 }
say 2 + 2;

Konrad Borowski

Posted 2014-05-30T06:54:35.963

Reputation: 11 185

Interesting this also changes what 1+1+2 and 3-1+2 returns. – Brad Gilbert b2gills – 2014-12-29T15:13:31.890

2It's interesting that the Haskell code that literally does exactly the same thing is the second highest voted answer. Maybe you should have pretended you didn't know how it works. – primo – 2014-06-06T11:37:02.350

3

+1 because you have no idea how this works.

– Justin – 2014-06-12T21:57:35.597

6

FORTH

: 2 ; : + 5 ; 2 2 +

I just redefined 2 to do nothing and + to put 5 on the stack.

protist

Posted 2014-05-30T06:54:35.963

Reputation: 570

6

Mathematica

First, our underhanded part (here directly entered to the kernel; in a notebook, you could delete that line afterwards!)

In[1]:= $Post=#+Boole[!SquareFreeQ@#]&;

Now, let's first verify that everything works as normal:

In[2]:= 2*3

Out[2]= 6

We can even test that 2+2 does really equal 4:

In[3]:= 2+2==4

Out[3]= True

And it certainly does not equal 5:

In[4]:= 2+2==5

Out[4]= False

So now, let's evaluate 2+2:

In[5]:= 2+2

Out[5]= 5

Oops!

$Post is a function that is applied to every expression after normal evaluation. ...& defined an anonymopus function, and # refers to the argument. SquareFreeQ gives true if the expression does not contain a factor that is a square (other than 1), ! is the logical not, as usual, anmd Boole converts the logical value into 0 for False and 1 for True.

Since 6 is square free, the first test is not affected by this: Adding 0 to 6 doesn't change anything.

One might expect an error on the tests giving True or False, but SquareFreeQ just gives True on such values (the same is true for the non-printed Null generated by the first line; otherwise it would have generated Null+1 which would have been printed). Also, the obviously meaningless addition True+0 is no problem for Mathematica; you can add 0 to anything (even a picture, if you desire) and it won't change anything. Therefore also those tests give the expected result.

Finally, we arrive at 2+2. This results in 4, which is not square free, thus $Post[4] evaluates to 5, which is what gets output.

celtschk

Posted 2014-05-30T06:54:35.963

Reputation: 4 650

5

Ruby

There are all sorts of bizarre meta-programming ways of doing this in Ruby, and I might post one at some point, but for now here’s a goofy bit of obfuscation.

def sum(*args)
  *arg_list,arg_enum=args
  arg_list.first + arg_enum.next
end

p sum(2,2)

histocrat

Posted 2014-05-30T06:54:35.963

Reputation: 20 600

1nice, but this isn't as much underhanded as it is obfuscated. – John Dvorak – 2014-05-30T18:00:03.227

2This looks like it calls Enumerator#next, but it really calls Fixnum#next. To get 4, the code should be def sum(*args); arg_enum = args.lazy.drop(1); args.first + arg_enum.next; end. – kernigh – 2014-05-30T22:01:52.043

5

Rebmu

I prefer objective golf to the more subjective "underhanded", but if that's the demand, here you go:

stLDtsTC43a&[5]

print do [2 + 2]

That outputs 5. The real payload here could be just 8 chars of poison, +: a&[5], substituting the arity-2 infix function that + is bound to by default with a prefix arity-1 function that always returns 5. Looks like other people have done the same thing and been downvoted, so I've upped the ante a bit with obfuscation.

The transparent version of the poisoning line would be:

+: function [dummy-parameter] [5]

But to try and mask it so no + appears in the poisoning code, it does stLDtsTC43a&[5] ... which translates to set load to-string to-char 43 to do the assignment. So it turns 43 into a character, then into a string, and loads it into structural code (as the single symbolic word +) to use the SET operator on.

After that line runs, basically + anything will will return 5. And since it isn't infix, it's not looking "behind" it to find a first parameter.

If evaluating to 5 were enough, you could just say 2 + 2. But if a print is desired, you can't merely print [2 + 2] and get 5, though. Because PRINT runs a REDUCE step, and keeps all of the values...so the evaluation becomes [2 5] and it prints both numbers. However, by calling the evaluator via DO (which returns the last result, discarding results of all prior evaluations) we throw away the 2...and all PRINT sees is the last value. + 2 is 5.


(Note: For anyone worried that this malleability points to an fatal flaw in Rebol/Red, I'll point out PROTECT:

>> protect '+

>> +: function [dummy-parameter] [5]
** Script error: protected variable - cannot modify: +:

It's a lot like a game of Nomic, for those familiar...)

HostileFork says dont trust SE

Posted 2014-05-30T06:54:35.963

Reputation: 2 292

5

T-SQL

declare @S varchar(max)
set @S = 0x0D0A6966206E6F74206578697374732873656C656374202A2066726F6D207379732E736368656D6173207768657265206E616D65203D202732202B203227290D0A626567696E0D0A20206465636C6172652040732076617263686172286D6178290D0A2020736574204073203D202763726561746520736368656D61205B32202B20325D270D0A20206578656320284073290D0A2020736574204073203D20276372656174652066756E6374696F6E205B32202B20325D2E5B205D28292072657475726E7320696E7420617320626567696E2072657475726E203520656E64270D0A20206578656320284073290D0A656E64
exec (@S)


select "2 + 2"

/* outputs a 5 */." "()

There is a schema named "2 + 2" with a scalar valued function named " " that always returns a 5. When you call a scalar valued function in SQL Server you have to specify the schema followed by period followed by the function name and parenthesis. The comment /* outputs a 5 */ is inserted after the schema name just to remove the focus from the required ." "() at the end.

create schema [2 + 2]
go

create function [2 + 2].[ ]() returns int as begin return 5 end
go

Mikael Eriksson

Posted 2014-05-30T06:54:35.963

Reputation: 249

I believe creating that schema should be part of the answer. – aaaaaaaaaaaa – 2014-06-06T15:38:30.103

@eBusiness I have updated the answer. I did it somewhat obfuscated to keep the challenge for someone who actually knows T-SQL. The select statement is enough to figure out how it is done since it is the only way the syntax valid. – Mikael Eriksson – 2014-06-07T05:17:28.233

5

Perl

use strict;

sub calculator ($) { @_ }

# Stack-based calculator, so start with an empty array
my @calculation = undef;

# First number to add is 2
push @calculation, 2;

# Operation
push @calculation, "+";

# Next number to add is 2
push @calculation, 2;

# We want to find out what it equals
push @calculation, "=";

# For debugging, let's see what the calculation is
print @calculation;

# Now print the result
print calculator(@calculation);

# And a blank line
print "\n";

tobyink

Posted 2014-05-30T06:54:35.963

Reputation: 1 233

my @calculation = undef;. I was wondering how to initialize an empty array, thanks! – primo – 2014-06-06T11:40:21.733

@primo, not sure if you were being serious, but the example above is not a great place to learn Perl from. my @calculation = undef doesn't actually result in an empty array, but rather a single-element array containing undef. It's a necessary step for this slightly obfuscated script to work. – tobyink – 2014-06-06T16:20:09.450

That was meant to be a subtle spoiler. Perhaps too subtle... ;) – primo – 2014-06-06T16:32:30.387

5

JavaScript

function add() {
  for (var i = 0; i < arguments.length; i++) {
    rv = (rv || 0) + arguments[i];
  }
  return rv;
}
if (add(0, 0) == 0) console.log("add(0,0) == 0");
if (add(0, 1) == 1) console.log("add(0,1) == 1");
if (add(2, 2) == 5) console.log("... umm ... what?");

Pretty easy to spot if you're looking for it.

svidgen

Posted 2014-05-30T06:54:35.963

Reputation: 311

+1 i see what you did there! very tricky! – markasoftware – 2014-06-06T22:54:51.593

5

Haskell (Proof by Curry-Howard Isomorphism)

A mathematical proof that 2 + 2 = 5 in Haskell. The proof is based on the Curry-Howard Isomorphism, where mathematical propositions are expressed as types in a programming language (here 2 + 2 == 5) and mathematical proofs of a proposition P are expressed as terms of type P (here undefined). The proof exploits diverging functions in Haskell to get the paradoxical Qed. data a == b ... defines propositional equality: the type that is inhibited (with Refl) if and only if a and b are judgmentally equal — i.e. a and b simplify to the same expression. The definition is equivalent to the definition of :~:.

{-# LANGUAGE DataKinds, PolyKinds, TypeOperators, GADTs #-}

import GHC.TypeLits

proof :: 2 + 2 == 4
proof = Refl

paradox :: 2 + 2 == 5
paradox = undefined

data a == b where
  Refl :: a == a

infix 4 ==

Konstantin Weitz

Posted 2014-05-30T06:54:35.963

Reputation: 1 083

5

DUP

It's simple: 2+2=5.

Try it here.

Hehe, good luck with this one.

Explanation

DUP treats most A-za-z as variables, albeit uninitialized. It pushes 2 uninitialized variables to the stack. 's pushes charcode of s to the stack. Whitespace is entirely ignored. simple pushes 6 more uninitialized variables to the stack, while : takes the top stack item (a variable) and sets it to the second from top stack item. 2 is pushed to the stack, + pops 2 numbers and adds them, 2 is pushed to the stack, = pops 2 numbers and checks for equality, and 5 is pushed to the stack.

Of course, that's all completely irrelevant, because just . outputs the top of the stack (in this case, 5).

Mama Fun Roll

Posted 2014-05-30T06:54:35.963

Reputation: 7 234

similar: http://codegolf.stackexchange.com/a/68608/46231

– cat – 2016-03-14T15:44:00.470

4

Ruby

class Fixnum
  def +(num)
    5
  end
end

2 + 2
# => 5

bioball

Posted 2014-05-30T06:54:35.963

Reputation: 161

4

HTML + CSS

<style>
#res {font-family: Audiowide;
width: 10pt;
overflow:hidden;
transform:scale(-1, 1);
-webkit-transform:scale(-1, 1);}
</style>
<link href='http://fonts.googleapis.com/css?family=Audiowide' rel='stylesheet' type='text/css'>

<div id="res">2+2</div>

http://jsfiddle.net/4rNLM/

aditsu quit because SE is EVIL

Posted 2014-05-30T06:54:35.963

Reputation: 22 326

4

C#

class Program
{
    private class Int32
    {
        public static int operator +(Int32 val1, Int32 val2)
        {
            return 5;
        }

        public static implicit operator Int32(int val)
        {
            return new Int32();
        }
    }

    private static void Main(string[] args)
    {
        Int32 num1 = 2;
        Int32 num2 = 2;

        Console.WriteLine(num1 + num2);
    }
}

UbbeLoL

Posted 2014-05-30T06:54:35.963

Reputation: 51

1+1 for a good demo of why I should continue to insist that my team use built-in types rather than System. types. – ClickRick – 2014-06-01T14:24:54.457

4

JavaScript

(NaN).constructor.prototype['\x74\x6f\x53\x74\x72\x69\x6e\x67'] = function(){ return-~this };

alert('2 + 2 = ' + (2 + 2).toString());

Demo Here

Overwrites the Number.toString method with one that returns one more than the current value. Uses unary negation on a bitwise not operation of the value.

nderscore

Posted 2014-05-30T06:54:35.963

Reputation: 4 912

4

PHP

<?php
// Somewhere in the initialization script
ob_start(function($buffer){return str_replace("4", "5", $buffer);});

// Many lines below
echo 2 + 2;
?>

That simple script will output 5.

ob_start($buffer) handles all the output until the script has finished executing. This is useful, for example, to minimize the html that you want to output, but here it's used only to change all 4 to 5.

Francisco Presencia

Posted 2014-05-30T06:54:35.963

Reputation: 181

4

PowerShell

And swing

function sum() {
    $args|%{("$($_[0])"-shr1)+("$($_[2])"-shl1)}
}

sum 2+2  #5

It's not quite "underhanded" in terms of the function, but if you were given a function called "sum", you'd think it would give you the proper value in return. Underhanded enough in my book.

This was an interesting problem to do in Powershell since you can "cast" in all sorts of goofy ways.

$_[0] is a [char], but by wrapping it with "$()" it makes it a string, eliminating three characters if you were to use [string].

I've discovered that using any sort of bitwise operator on a string that can be interpreted as an int, then it casts to int and does the operation.

Powershell also allows for pretty much any character to be part of a variable or function name thus:

function 2+2 {
    5
}

Can be called like . ${Function:2+2} and it will give you 5

SomeShinyObject

Posted 2014-05-30T06:54:35.963

Reputation: 953

4

COBOL

I considered how, in a 10,000-line program, most of the DATA DIVISION never gets properly looked at, so I was going to use double-think things like defining ONE as 2 and TWO as 1, or go for misleading 88-level values, or abuse such names as TWO-ONE with a value other than 1 in a COMPUTE, but figured they were too easy. Actually, in a 10,000-line program, they're easy to miss, but this is just a fragment, so they'd not get so easily lost.

That left me really, really not regretting leaving COBOL behind several years ago, and chose instead to prove that 1 + 2 + 1 = 5 in COBOL-land just as easily as in other languages.

   data division.
   working-storage section.
   77  one type Int32 value 1.
   77  two type Int32 value 2.
   77  result type Int32 value 0.

   procedure division.
       move one to result.           *>   RESULT <- 1
       add two to result.            *>   RESULT <- 3
       multiply two by one.          *>   TWO    <- 2
       add one to result.            *>   RESULT <- 4
       display '1 + 2 + 1 = ' result.

Result:

1 + 2 + 1 = +0000000005

.

The MULTIPLY verb puts the result in the second operand, not the first as might be inferred by the casual reader.

ClickRick

Posted 2014-05-30T06:54:35.963

Reputation: 245

4

APL

I thought this was nice to share, it happened to me to stumble on this kind of error. Plus, there was no APL answer yet :-).

a←¯1          we set a to be -1
2+a+←3        APL executes righternmost operations first, so 3 is summed to a, obtaining 2
              so proceeding to the next operation (2+) we should get 4 but...
5

This would work if it was split on 2 lines (a+←3 ⋄ 2+a) but doesn't work here because the assignment operation (←) has an implicit result which is the right argument of the assignment (in this case 3). So the 2 is added to the result of the assignment, not to a.

Moris Zucca

Posted 2014-05-30T06:54:35.963

Reputation: 1 519

3

C#

using System;

namespace AdditionFoo
{
    class Number
    {
        private int m_value;

        public Number(int value)
        {
            m_value = value;
        }

        public static Number operator +(Number c1, Number c2)
        {
            if( (int)c1 == (int)c2 && c2 == 2)
                return 5;
            return c1.m_value + c2.m_value;
        }

        public static implicit operator Number(int b)
        {
            return new Number(b);    
        }

        public static implicit operator int(Number b)
        {
            return b.m_value;
        }

        public override string ToString()
        {
            return m_value.ToString();
        }
    }

    class Program
    {
        static void Main()
        {
            var a = (Number)2;
            var b = (Number)2;

            var c = a + b;

            Console.WriteLine(a + "+ " + b + "= " + c);
            Console.ReadLine();
        }
    }
}

user21774

Posted 2014-05-30T06:54:35.963

Reputation: 41

3

C++

#include <iostream>
using std::cout;


int main(void)
{
    char const * const one = "345678910";
    //copy template string
    char * two = new char[strlen(one) + 1];

    strcpy_s(two, strlen(one) + 1, one);

    //but make this one a zero
    *(two + 3) = 0;

    //not working for some reason?
    cout << two + 2;

    delete[] two;
    return 0;
}

Kik

Posted 2014-05-30T06:54:35.963

Reputation: 131

Note that here in PPCG when a question asks for a program, we generally include everything necessary for compilation, so e.g. in C++ you need a main() function. – user12205 – 2014-05-30T22:32:58.457

3

Python 3

>>> ₓ2 = 3

>>> print("2+2 =",ₓ2+2)

2+2 = 5

Don't downvote; try it by cut and pasting.

Hint:

To find out, hold Ctrl+= (Zoom) and look carefully:

Additional Hint:

Look at the 2 in 2=3 The x next to it makes it assign: x2 = 3 I made all the text small to reduce the chances of noticing the code was small.

Ramchandra Apte

Posted 2014-05-30T06:54:35.963

Reputation: 189

31'What is this, Code Golf for Ants?!' – MrLore – 2014-05-31T11:53:57.483

1@MrLore I would like to inclusive and allow ants to read it . – Ramchandra Apte – 2014-05-31T11:57:50.060

@Schilcote you can delete your spoiler comment; I have added a spoiler. – Ramchandra Apte – 2014-06-01T03:56:21.763

-1. This is essentially the same as the homoglyph trick, except less underhanded. Also, it breaks formatting.

– John Dvorak – 2014-06-01T05:55:19.127

@JanDvorak Thanks, I didn't know. – Ramchandra Apte – 2014-06-01T06:27:13.720

3

Coq

Lemma silly : 2 + 2 = 5.
Proof.  admit. Qed.


(* We can now prove all other sorts of broken things *)
Example consequence : 5 = 6.
Proof.
    assert (expand : 6 = 1 + 5).
        simpl. reflexivity.
    rewrite -> expand.
    assert (expand2 : 1 + 5 = 1 + 2 + 2).
        rewrite <- silly.
        simpl.
        reflexivity.
    rewrite expand2.
    simpl.
    reflexivity.
Qed.

This (un)fortunately doesn't prove that 2 + 2 = 5, since admit is the "hey compiler, trust me on this on" value, but you can use it in later proofs.

Theo Belaire

Posted 2014-05-30T06:54:35.963

Reputation: 169

3

C/C++

#include "hidden.h"
int main()
{
    printf("%i\n", 2 + 2);
    getchar();
    return 0;
}

hidden.h:

#define + + 1 +

The answer (if it's not obvious)

Unicode/Preprocessor hacks: The + symbol is a unicode symbol, which means it doesn't count as the + operator, so it's possible for the preprocessor to re#define it. main itself uses +, but without seeing the #define beforehand, anyone would think it were just a normal + operation.

Pharap

Posted 2014-05-30T06:54:35.963

Reputation: 195

Note that I separated the code into two files for the sake of keeping the trick hidden for those who like figuring out how these things work. – Pharap – 2014-06-06T23:06:04.040

3

Java

public final class MyMath {
    public static void main(String[] args) {

        boolean isFive = ((2 + 2) == 5);

        if(isFive = true) {
            System.out.println("2 + 2 = 5");
        } else {
            System.out.println("2 + 2 is not 5");
        }
    }
}

There is a small typo in the isFive check... I've actually seen this happen in production code :-(

Roy van Rijn

Posted 2014-05-30T06:54:35.963

Reputation: 1 082

1There was an attempted linux backdoor hack that was this trick, if(user = 0)... or something, making the user root, not checking if the user was root. – ACarter – 2014-06-06T10:11:22.520

3

Emacs Lisp

(defadvice + (before freedom-is-slavery activate)
  (when (ad-get-args 0)(ad-set-arg 0 (or (and (= 2 (length (ad-get-args 0))) (= 2 (ad-get-arg 0)) (= 2 (ad-get-arg 1)) 3) (ad-get-arg 0)))))

(+ 2 2) ;; => 5

Emacs advice allows you to define code that runs before, after, or around the main body of a function to modify its behavior. In this case, I specify that every time + is executed, the arguments should be checked and if there are two arguments that are both 2, set the first argument to 3 before passing them into the main body of +.

Jordon Biondo

Posted 2014-05-30T06:54:35.963

Reputation: 1 030

hows it working? – masterX244 – 2014-07-23T17:14:00.880

I've updated the post to explain the code. There was also a typo in the code but it will work now if you try it out. – Jordon Biondo – 2014-07-23T17:20:37.850

thx, now its obvious – masterX244 – 2014-07-23T17:22:09.497

3

C#

using System;
class Program
{
   static void Main()
   {
      double \u01bb;
      unchecked
      {
         \u01bb = (double)((uint.MaxValue + 3) + 0.5);
      }
      Console.WriteLine(ƻ + ƻ);
   }
}

\u01bb is the unicode escape sequence for ƻ. Since ƻ is technically a letter, it can be used as a variable name. The 1st thing the C# compiler does is convert all escape sequences to the correct unicode characters, so my program utilizes overflow to set the value of ƻ to 2.5 in a roundabout way.

LVBen

Posted 2014-05-30T06:54:35.963

Reputation: 290

3

Batch

@echo off
set a=2
set /a a+=2>nul^
::No 3
echo %a%

Sets a to equal 2, then adds 2 to a redirecting stdout to nul. So %a% should output 4. Only a harmless comment before the output.

The trick is that >nul is actually 2>nul redirecting stderr to nul. Due to the carat after nul, it ignores the newline and is actually redirecting stderr to nul::No. Evaluating instead set /a a+= 3, the redirection is considered before the command is executed. Unfortunately the carat makes it very obvious, I couldn't think of anything more underhanded.

unclemeat

Posted 2014-05-30T06:54:35.963

Reputation: 2 302

3

C

Two fun entries,

#include <stdio.h>
int main(x)
{   
    int a = 2;
    int b = 2;
    int c = a + b;
    printf("%d + %d%n = ", a, b, &c);
    printf("%d\n", c);

    return 0;
}

and

#include <stdio.h>
#include <string.h>

int main(x)
{   
    int a = 2;
    int b = 2;
    int c = a + b;
    memset(&x, c+x, 9);
    printf("%d + %d = %d\n", a, b, c);

    return 0;
}

Run the second program at your own risk, it may set your PC on fire.

The magic:

The first program I takes advantage of the little-known format specified: "%n" which instead of printing anything, it actually writes to the location specified the number of characters that were written up to that point. In my code it was "2 + 2" which is 5. The code then goes on to print that value resulting in the final output of "2 + 2 = 5". The second is UB, I take advantage of how GCC lays out the variables which is: argc, argv, c, b, a (in THAT order) and the fact intel is little endian. Note in my example, to aid the confusion I renamed argc x and intentionally omitted argv (which GCC implicitly includes back). Once you understand that the code is pretty clear, we are writing (c+x) which is 5 over argc and argv to get to c. The code then goes on to print "2 + 2 = 5".

David

Posted 2014-05-30T06:54:35.963

Reputation: 141

how to the strangeness of C ddoes the magic work? – masterX244 – 2014-12-31T16:57:02.660

@masterX244 I added an explanation – David – 2014-12-31T21:47:33.427

Nice hack at variant 2 :). black magic at its finest – masterX244 – 2015-01-01T01:29:16.177

3

Scratch

reset timer
wait (2) secs
wait (2) secs
say ([ceiling v] of (timer))

Waiting 2 seconds, then another 2 seconds. 4? Nope - says 5.

Scimonster

Posted 2014-05-30T06:54:35.963

Reputation: 2 905

3

Ruby

%w(2+2).pack("m").size

Some Ruby pack magic!

%w(2+2).pack("m") returns "Misy\n" which is a 5 character string.

Biketire

Posted 2014-05-30T06:54:35.963

Reputation: 200

3

R

> `+` <- function(e1,e2) base::`+`(base::`+`(e1,e2),1)
> 2+2
[1] 5

Kun Ren

Posted 2014-05-30T06:54:35.963

Reputation: 181

3

><>

Nowhere near the best, but it was fun to make

3a*4+:02p:c2p:b3p\
03p5a*3+c3pab*d3p\
 import Math     \
 print(2+2)     ;\

Output

5

Explanation

The first two lines of keyboard mash is actually code that puts quotes around import math and print(2+2), and also puts 5n immediately afte the ending quote of the 4th line. ><> is stack-based, so 5n pushes 5 onto the stack, and n pops off the top value and prints it as a number.

clap

Posted 2014-05-30T06:54:35.963

Reputation: 834

3

TI-BASIC:

With all of these answers redefining the value of 2, we need to make sure we really have 2, not some impostor. So let's construct 2 from 0, like the set theorists.

PROGRAM:FOUR
"+1"→u         ;successor function.
0→Min          ;make sure  is in the domain
0→
u(→           ;=1
u()+u(        ;u(1)+u(1) = 2+2 = 4, obviously.

Let's try it...

prgmFOUR
               5

When the calculator calculates the sequence function u at a given value, for example u(n), it sets n to the value, evaluates the string stored in u, and then increments n. Why? That's a good question, but I suspect it has something to do with the fact that when the TI-84 evaluates any call to u, it first evaluates u at every n less than the value given, regardless of whether the function is actually recursive (yes, it takes linear time in n to get a single value of u).

lirtosiast

Posted 2014-05-30T06:54:35.963

Reputation: 20 331

3

C89

int main()
{
    int a;    
    a = 2 + 2//**/(2.f/3.f)
    ;
    printf("%d\n", a);
    return 0;
}

A little explanation:

In C89 there just existed the multiline comment like this: /* This is a comment*/, but not the single line comment: //This would be an syntax error in C89 or previous versions so in this code, which doesn't see the single line comment but just sees the /**/as a starting and immediately ending comment. the program after parsing really does:

a = 2 + 2 / (2.f/3.f);

Zaibis

Posted 2014-05-30T06:54:35.963

Reputation: 1 663

3

Whitespace, (looks like C++)

I don't know if this qualifies, but I thought it was fun

raw paste data here.

online interpreter here.

#include<iostream>               

int main() {                
    std::cout<<2+2;




    return  0;      



}

If you run it in C++ it prints

4

If you run in whitespace it prints

2+2=5

Liam

Posted 2014-05-30T06:54:35.963

Reputation: 3 035

1I feel the urge to remove all the newlines, as I've done countless of times on newbie posts on SO. =P – Stewie Griffin – 2015-11-08T12:59:40.417

3

MATLAB

In MATLAB, the plus function can be called in two different ways, either by using +, or writing plus. If you try to add values of different types, for instance a cell with an integer, you'll get an error stating what the error is, for instance:

plus(3,{3})
Undefined function 'plus' for input arguments of type 'cell'.

plus(2,2,2)
Error using  + 
Too many input arguments.

This of course, is helpful, as it tell's you what the problem is: You cannot add a cell and an integer, and for some reason, you can't add three integers either. Typing help plus won't help you a lot, it just tells you that the plus-function can add two arrays.

The best approach seems to be to create a very simple plus-function that is both simple to read, and simple to understand.

plus=@(x,y) x + y + logical((x==(isnumeric(x)+isfinite(x)) & y==(isnumeric(y)+isfinite(y))));

This function checks if both arguments, x and y are numeric and finite. If not, it will fail, just as the original plus-function. The advantage is, you still get to know what the error is, but you also get too know where, and why!

plus(3,3)
ans =
     6

plus(3,{2})
Undefined function 'plus' for input arguments of type 'cell'.
Error in @(x,y)x+y+logical((x==(isnumeric(x)+isreal(x))&y==(isnumeric(y)+isreal(y))))

And of course:

plus(2,2)
ans =
     5

x==(isnumeric(x)+isreal(x)) returns 1 if x = 2, because the two functions isnumeric and isreal will both return 1, thus 1+1. The same goes with y==(isnumeric(y)+isreal(y)) of course. Now, we check if both those conditions are true, and return a logical 0 or 1: logical((x==(isnumeric(x)+isreal(x))&y==(isnumeric(y)+isreal(y)))). The logical function is strictly not necessary, but I think it makes it a bit harder to spot (for an untrained eye of course). In MATLAB, boolean values can be added to integers, so for x & y == 2, this will return 2+2=5. For any other values, it will return the correct answer.

Stewie Griffin

Posted 2014-05-30T06:54:35.963

Reputation: 43 471

And how does this output 2+2=5? – Sanchises – 2015-11-08T12:40:04.280

@sanchises, I'll take that comment as a good sign, at least since I know you know MATLAB =) Have a look here.

– Stewie Griffin – 2015-11-08T12:55:28.393

Mostly, I was missing last bit of code where it says plus(2,2) = 5 - I was wondering whether your actually got the point of the challenge :) Let me see if I can figure it out before reading your spoiler. Edit: hehehe. Who doesn't love weak typing... – Sanchises – 2015-11-08T15:37:27.290

Jep, although mostly because I used to program my TI-BASIC games like that. Shame I long since lost my calculator... – Sanchises – 2015-11-08T18:29:52.573

3

MATLAB

I think this one can be quite deceiving as well.

disp(fprintf('2+2 ='))

Printing

2+2 =     5

Or alternatively

fprintf('%d\r',fprintf(' 2+2='))

Printing

2+2=5

slvrbld

Posted 2014-05-30T06:54:35.963

Reputation: 619

1How does it work? How does fprintf('2+2 =') come up with a 5? – Cyoce – 2016-01-05T16:17:04.940

1@Cyoce fprintf returns the number of characters successfully written. – FryAmTheEggman – 2016-01-05T16:20:00.137

I really like this approach... (You had my upvote two weeks ago!) =) – Stewie Griffin – 2016-01-19T11:48:57.410

3

Octave

To ensure compatibility with other programs and languages, outputting the result as a string without the default ans = part is the most sensible thing to do. This can be achieved like this:

disp(num2str(+('2+2'))(1))
5

The ASCII-code for 2 is 50. '2+2' is a vector with the characters with ASCII-codes: [50 42 50]. This is implicitly converted to integers using +, and then converted to a string '50 43 50' using num2str(). Using Octave's direct indexing you can obtain only the first element of this string, 5. This is then displayed using disp().

Stewie Griffin

Posted 2014-05-30T06:54:35.963

Reputation: 43 471

2

Javascript

var num1=1;
var num2=2;
alert(num1 + " + " + num2 + " = " + Math.ceil((num1/10+num2/10)*10));

Although it's kind of cheaty and not really valid I decided to answer it anyways because I can.

As I'm sure most of you know, this relies on the fact that 0.1 + 0.2 = 0.300...004 in Javascript. That said, this script obviously only calculates 1 + 2 = 4 (instead of 2 + 2 = 5) but gives the correct answers for all other numbers

Christoph Böhmwalder

Posted 2014-05-30T06:54:35.963

Reputation: 681

2

JavaScript

This isn't really particularly inspired, but:

a=atob(btoa('2+2')+'LTIrMw==');eval(a)

or perhaps

a=atob(btoa('2+2').replace(/i/,'y'));eval(a)

user21677

Posted 2014-05-30T06:54:35.963

Reputation:

2

Python 3

A rather trivial example from me.

Imagine the following hidden in an import somewhere; maybe modify a prank-ee's math.py (so that only non-trivally mathematical programs get the error)

#nothin to see here folks
import builtins
class int(builtins.int):
    def __add__(self,other):
        if self==other==2:
            self=3
        return builtins.int.__add__(self,other)

To test, combine with this:

if __name__ == '__main__':
        #Input returns strings; we must convert to ints
        lights1=int(input("How many lights are in set 1? "))
        lights2=int(input("How many in set 2? "))
        print("There are",lights1+lights2,"lights!!!")

For whatever reason, super() doesn't work inside the fake int. Which is too bad; otherwise, I'd set builtins.int to be the "evil" int as well, making the real default int unrecoverable (and making builtins.int is int be true, making it harder for the victim to confirm their suspicions).

Of course, no matter what this won't work on int literals; Python directly turns those into the default int objects even if builtins.int is set to something else. Only things that are converted to ints will be affected.

Reminds me of the stage hypnosis trick where you convince your subject there is no number six and then have him count his fingers; first the left, then the right, then all of them together...

Schilcote

Posted 2014-05-30T06:54:35.963

Reputation: 139

1This question is an [tag:underhanded] contest. Answers should appear that they will output 4, but in reality output 5. Your submission does not seem to be trying to hide the fact that it will output 5, so it may not be considered a very good answer for this question. Anyway, welcome to PPCG! :) – user12205 – 2014-05-31T20:40:05.310

It hides it just fine; there's clearly a comment above the "malicious" code telling readers not to look at it. I had some ideas to make it a little more devious; editing now. – Schilcote – 2014-05-31T21:28:02.537

2

C

How can this be!? For the maths are broken! The sum of the length of two strings with both the length of two is five.

Since string length is isomorphic to the set of Natural numbers, I decided to use strings for this challenge.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
   char* str1 = "ab";
   char str2[4] = "cd";
   char z = 0x90;

   str2[3]=0x00;
   memcpy(str2+2, &z, 1); 

   printf("%d\n", strlen(str1) + strlen(str2));

}

strlen will return the length of address calculated where the first null byte is detected - start address

Gary Drocella

Posted 2014-05-30T06:54:35.963

Reputation: 131

2

Javascript

var number = 3;   //set variable
numbеr = 2;       //redefine it
alert(number+numbеr) //alerts 5. (what?!?!)

JSFIDDLE

nicael

Posted 2014-05-30T06:54:35.963

Reputation: 4 585

@Pharap You can even Ctrl + F e... seigh – YoYoYonnY – 2016-01-31T23:48:10.190

2@YoYoYonnY Don't Ctrl + F e, use Ctrl + F е instead, makes things easier :P – Pharap – 2016-01-31T23:52:50.120

2That's pretty good. Could you post a spoiler explaining it? – Theo Belaire – 2014-06-03T21:18:03.680

5

This hack has been presented multiple times on this question (and even in this language) already. It's officially now on the not funny list.

– Caleb – 2014-06-04T07:59:37.390

1oh it's the variables that look the same but aren't, isn't it? – ACarter – 2014-06-06T10:19:22.020

@ACarter Guess. – nicael – 2014-06-06T10:48:46.610

1It's the e that does it – Pharap – 2014-06-06T23:19:21.377

2

PHP (<5.3.11)

Okay, so it's not quite 2+2=5, but 1+1+2=5:

echo 0x0 +1 +1 +2;
// 5

Thanks to a weird issue in the PHP parser, the first 0x0 +1 is interpreted as a hexadecimal literal and an addition, in other words, it becomes (0x01+1).

p.s.w.g

Posted 2014-05-30T06:54:35.963

Reputation: 573

I had to go back to PHP 4.4.9 to make that work (current stable is 5.5.13). You should probably consider updating your interpreter - 4.4.9 was released Aug. 2008. – primo – 2014-06-06T11:46:50.137

@primo It seems like this bug was fixed with 5.3.11. I've added a note about the compatible versions. – p.s.w.g – 2014-06-06T11:54:45.107

2

CoffeeScript

addNums = () ->
    document.body.textContent=2+2;
addNums();

Try it here

A kind've spoiler: it uses some invisible characters, and (at least on my machine) when you copy paste it it doesn't copy the special characters, and it says 4 when you run it (on the link it does what i meant for it to do and prints 5

Actually try to figure it out before looking at the spoiler

Look at the url of the "Try it here" link above. Look at my username. Nope, definitely not sucspicious

Still don't get it?

There's no invisible characters. I made the "online coffeescript compiler" that the link is to myself. It's a fakey compiler, and doesn't do what it's supposed to. Instead of running the code that you see on the page, it sets document.body.innerHTML to 5, regardless of what it's "compiling". You can see in this jsfiddle that the code actually prints 4 in a legit compiler

markasoftware

Posted 2014-05-30T06:54:35.963

Reputation: 346

How does this work? – ACarter – 2014-06-06T10:13:15.560

1@ACarter i don't want to say in the comments, so I'll update the question. I guess my current spoiler isn't obvious enough – markasoftware – 2014-06-06T22:50:46.090

2

MySQL

Here my simple SQL solution to the problem:

Database structure:

create table doublethink(`2+2` int);
insert into doublethink values(5);

Query:

mysql> select `2+2` from doublethink;
+------+
| 2+2  |
+------+
|    5 |
+------+

The trick is that in MySQL column names are escaped by backticks. So 2+2 is not evaluated, but used as a column name.

MarcDefiant

Posted 2014-05-30T06:54:35.963

Reputation: 996

2

GolfScript

[123 45 49 42 45 41 125 58 43 59]+~# These are my lucky numbers.

2 2+

The evaluated string redefines the addition operator as {-1*-)}:+, i.e., normal addition incremented.

-5...??./*-2/:2;

2 2+

-5...??./*-2/:2 saves -5 * (-5 ** (-5 ** -5) / -5 ** (-5 ** -5)) / 2 (also known as 2.5) in the variable 2.

{;5print}:puts

2 2+

This overwrites the implicit output function puts with a new function that always prints 5.

Dennis

Posted 2014-05-30T06:54:35.963

Reputation: 196 637

2

Javascript (should work in a bunch of other languages too):

It adds what looks like 2+1+1

Math.ceil((0.2+0.1)*10)+1

Try doing the math yourself:

  • (0.2+0.1)*10 = 3
  • Math.ciel(3) = 3
  • 3+1 = 4

This works because of how floating point decimals work. 0.2+0.1 is just a little bit more than 0.3. Multiplying it by ten and then rounding it up gives us 4. Then we add an extra 1 because it should be 3 by now. When we do that, the result is 5.

potato

Posted 2014-05-30T06:54:35.963

Reputation: 111

I posted almost the exact same answer. The strangeness of floats can really make 2+2=5. – wolfhammer – 2014-09-05T20:08:24.847

2

Perl 5

Example 1

(2 != 3) ? $x = 2 + 2 
         : $x = 2 + 3;
print $x;

? defines an lvalue and has higher precedence than assignment, so the code is equivalent to ((2 != 3) ? ($x = 2 + 2) : $x) = 2 + 3.

Example 2

@a = ("one", "2");
$x = length @a;
$x += length reverse @a;
print $x;

Length is string length, not list length, and hence expects a scalar. Arrays in scalar mode return their length, so length @a = length "2" = 1. Reverse in scalar mode concatenates and reverses its input, so length reverse @a = length "2eno" = 4.

Example 3

print (2 + 3) - (2 + 3) + (2 + 2);

The first set of parentheses define the arguments to the builtin print; the remaining calculation is applied to the return value of print and discarded.

Uri Granta

Posted 2014-05-30T06:54:35.963

Reputation: 2 675

2

TI 30 Calculator

2nd ÷ +1

Examples

3+4 = 8

9*5 = 46

sqrt(16) = 5

The variable K gets appended to every executed calculation. So if K is set to +1, +1 is getting appended to every executed calculation. That means when you type 5+5 and press enter, the calculation gets to 5+5+1.

Note: You can make your calculator calculate normal again by doing a memory reset(2nd 0 2 or by using the reset button at the back of your calculator)

CocoaBean

Posted 2014-05-30T06:54:35.963

Reputation: 309

2

Mathematica

The "simple" solution of just redefining 2+2 as 5:

> Unprotect[Plus];
> Hold[Plus[2, 2]] ^:= Hold[5]

> 2 + 2 // Hold // ReleaseHold
5

This was suprisingly difficult, because Mathematica keeps evaluating plus before any of my substitution got the chance to replace it.

There is also the alternative version on the same theme, redefining 4 to be equal to 5:

Unprotect[Integer];
head_[a___, 4, b___] ^:= head[a, 5, b]

Print[2+2]
Plot[x^2, {x,0,2+2}]

Note that the second example won't work* though, due to this code replacing the number 4 with 5 everywhere. This means that any internal Mathematica functions that happen to use the number 4 somewhere will get "interesting" behaviour. XD

*Well it almost works in this case, try replacing a smaller number instead, to get even more interesting results. I had the documentation page crash for me once.

Hjulle

Posted 2014-05-30T06:54:35.963

Reputation: 479

I know that you were supposed to hide the fact, and that "just redefining 2+2=5 is not creative", but the fact that you can make it hold litteraly, even for internal Mathematica code made me submit this anyways. – Hjulle – 2015-02-25T15:57:04.417

2

C++

This is similar to some other methods, but I think slightly sneakier because at a glance it looks extremely straightforward.

   #include "iostream.h"
    int main()
    {   
        int TWO = 2;
        int F0UR = 4;

        std::cout<< TWO << " + " << TWO << " = " << FOUR;
        return 0;
    }

This prints to the console:

2 + 2 = 5

The trick here is that "iostream.h" is actually a local file containing

 
 #include < iostream >
 #define FOUR 5 
 
Here the macro FOUR is defined to be 5. In the code body, the integer is F0UR, using a zero instead of the letter "O" as the second character. Depending on the font used, this difference can be very difficult to detect.

Liam

Posted 2014-05-30T06:54:35.963

Reputation: 3 035

2This doesn't really count, IMHO, since you didn't include all the source code. – mbomb007 – 2015-10-06T21:26:54.703

I know, It is kind of a cheat. – Liam – 2015-10-06T21:31:28.350

2

MATLAB

fprintf('%c.%c',num2str(int8(num2str(sum(2,2)))))

Ok, so not quite 2+2, but it does look like it does the sum of 2 with 2 to make 5.0. Now I will leave you to ponder quite how it ends up being 5.0 given ASCII and all.

:)

Just in case you are trying to work out how 50+2 equals '50', you should probably look up the documentation of sum. All is not quite what it seems ;)

Tom Carpenter

Posted 2014-05-30T06:54:35.963

Reputation: 3 990

2

AppleScript

According to this answer on the Programmers SE site, the ¬ symbol is "negation", or "not". Therefore, by all reasoning, the following code should absolutely return 4.

if 2 + 2 ≠ 5 then ¬
    return 5
return 4

Because if 2 + 2 does not equal 5, then do not return 5, return 4.

Output:

5

In AppleScript, the ¬ character actually means "concatenate the next line onto this one". So it will actually execute return 5 if 2 + 2 ≠ 5.

Addison Crump

Posted 2014-05-30T06:54:35.963

Reputation: 10 763

2

C

#include "stdio.h"

int main() {{
     int i,j,s,d;
     /* auto test */
     for(i=1;i<=2;i++)
     {{
         j=i;
         d=diff(i,j);
         s=sum(j,j);
         if( d != 0 || s != 2*i ) abort();
     }}
     /* redo it out of loop to be really sure */
     d=diff(i,j);
     s=sum(j,j);
     printf("%d-%d=%d\n",i,j,d);
     printf("%d+%d=%d\n",j,j,s);
     return 0;
}}

diff(a,b) {{ int i=a,j=b; return i-j; }}
sum(i,j) {{ int i,j; return i+j; }}

It outputs:

$ clang test1.c 2>/dev/null
$ ./a.out
3-2=1
2+2=5

This is my first program in C, could you help me?

NOTE

I came to totally distrust the integer arithmetic unit, so I modified my functions with the aim of using the floating point unit instead:

copy(int*a,float*b){*b=*a;}
diff(a,b) { float i,j; copy(&a,&i); copy(&b,&j); return i-j; }
sum(i,j) { float a,b; copy(&a,&i); copy(&b,&j); return a+b; }

but no luck so far, the floating point arithmetic is equally broken!

$ clang test2.c 2>/dev/null
$ ./a.out
3-2=1
2+2=5

aka.nice

Posted 2014-05-30T06:54:35.963

Reputation: 411

Just use proper K&R definition style - sum(i,j) int i,j; { return i+j; } – ugoren – 2016-01-19T12:07:06.327

What do the double braces even mean? i can has explanashun – cat – 2016-01-19T18:01:20.237

@cat an extra pair of braces just delineate variable scoping in this case. This scoping was necessary to obtain UB with temp variable i,j shadowing sum() parameters i,j. Otherwise c compilers (gcc, clang, ...) see the two declarations (implicit int parameters and temp) as conflicting because at same scope... – aka.nice – 2016-01-19T23:54:15.430

2

Python 3

An extremely lame one, inspired by this MATLAB answer.

>>> import sys
>>> sys.stdout.write("2+2= ")
2+2= 5

sys.stdout.write always slaps the number of written chars on the end of the bytestream. I don't know why, or how to make it stop, but useful indeed.

Proof it Works On My Machine™

Here's more proof it works.

Also:

$ python3.4
Python 3.4.3+ (default, Oct 14 2015, 16:03:50) 
[GCC 5.2.1 20151010] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.write("hello")
hello5
>>> 

cat

Posted 2014-05-30T06:54:35.963

Reputation: 4 989

Sorry, But I do not have this behaviour at all ! – dieter – 2016-01-05T16:49:46.693

Works On My Machine™. Ideone doesn't have it either, but my default installation of Python 3.5 on Ubuntu 15.10 has this behaviour. – cat – 2016-01-05T16:52:14.033

It does not, indeed, work on Python 2, though I thought it did, sorry. – cat – 2016-01-05T16:54:21.640

Proof? – cat – 2016-01-05T17:04:29.120

More proof – cat – 2016-01-05T17:12:39.320

http://imgur.com/tVZKvzy I confirm that it rolls only under python 3, not python 2 - – dieter – 2016-01-06T08:32:11.173

2

C++

Didn't check all the answers but no C or C++ answers to date use this approach.

int main()
{
    // we can do this by adding an int and a float; takes advantage of an FPU bug
    char *sum = "2 + 2.0";
    int total = 0;
    for (int i = 0; sum[i]; i++)
        total = (total+sum[i]) & strlen(sum); // AND op prevents buffer overflow
    printf("%s = %d\n", sum,total);
    return 0;
}

Output: 2 + 2.0 = 5

Dave the Sax

Posted 2014-05-30T06:54:35.963

Reputation: 151

Nice answer :-) – cat – 2016-03-04T22:18:14.760

1

GolfScript

2,~2,~],

What the program does:

2, generates the array [0 1]
~ dumps the array onto the stack
] gathers the items on the stack into an array
, gets the array length

If you delete the ], part, the program prints 0101 - 4 characters. But if you run the full program, it prints 5.

Explanation:

At the beginning of the program, the standard input is pushed on the stack as a string. If there is no input, an empty string is still pushed. That string gets collected into the array too, so the array will actually be ["" 0 1 0 1]

aditsu quit because SE is EVIL

Posted 2014-05-30T06:54:35.963

Reputation: 22 326

1

Java

Using reflection:

import java.lang.reflect.Field;

public class TwoPlusTwoTest {

    public static void main(String[] args) throws Exception {
        Field field = String.class.getDeclaredField("value");
        field.setAccessible(true);
        field.set("\u0032", new char[] {51});
        int twoPlusTwo = Integer.parseInt("2") + 2;
        System.out.println(twoPlusTwo); //5
            /**** Another ***/ 
        field.set("\u0032\u0020\u002B\u0020\u0032", new char[] {'\u0035'});
        System.out.println("2 + 2".equals("5"));
    }
}

Reflectively accesses the internal array field, named value, that String is backed by, and sets its value to 3. Because all constant Strings are interned and are accessed from the pool of constant Strings, this results in the String literal "2" actually refer to a char array with value {3}.

JavaScript

Using an overloaded valueOf:

String.prototype.valueOf = function () {
  return 3;
}
Array.prototype.valueOf = function () {
  return 3;
}

console.log(2 + [2]); //5
console.log(2 + new String(2)); //5

Array.prototype.valueOf = function () {
  return 2.5;
}

console.log([2] + [2]); //5

The valueOf method is called by the engine when an object is used in a numeric context.

c.P.u1

Posted 2014-05-30T06:54:35.963

Reputation: 1 049

1

JavaScript

This is meant to be run a browser's development console. It is horrible code.

+function(p){
    var o=p.toString;
    p.toString=function(){
        return (this-4)?o.call(this):'5'
    }
}(Number.prototype);

(2+2).toString()

Edit: nderscore hid this technique way better, and you should check it out. The only upside to my code is that 4 is the only value affected.

Keen

Posted 2014-05-30T06:54:35.963

Reputation: 261

1

Factor

IN: scratchpad << "\x32" create-in 5/2 define-constant >>

IN: scratchpad 2 2 + .
5

This exploits the parser, particularly the parse-datum word which searches a token for an already defined word, then if not found, tries to parse it as a number. Usually, we disallow words from being defined by a number using scan-word-name, but that doesn't prevent you from doing it yourself as in the example above.

mrjbq7

Posted 2014-05-30T06:54:35.963

Reputation: 41

1

Befunge93

2+2=? The answer is printed here: @.+!!

Try it online.

Explanation

The = functions as a mirror for the instruction pointer (in Befunge93), so the phrase itself is not "executed". The pointer goes this way:

2 - put 2 on the stack
+ - add 2 to 0 (i.e. do essentially nothing)
2 - put another 2
= - instruction not defined: inverse the direction of the pointer
2 - put another 2
+ - add 2 to 2 - put 4
2 - put 2. Wrap to the end of the line
! - logical negation for 2: put 0
! - logical negation for 0: put 1
+ - add 1 to 4 - put 5
. - print 5
@ - exit

har-wradim

Posted 2014-05-30T06:54:35.963

Reputation: 150

1

Javascript

Not going to win any prizes with this one, but I like it.

console.log(
  // +~~~~~~~~~~~~~~~~+ //
  // |     __  _____  | //
  // |  __|  ||   __| | //
  // | |  |  ||__   | | //
  // | |_____||_____| | //
  // +~~~~~~~~~~~~~~~~+ //
  "" -0-~~~ (2+2) -~~0- ""
  // +~~~~~~~~~~~~~~~~+ //
);

Plus it's been ages since I've seen any ASCII art...

Pebbl

Posted 2014-05-30T06:54:35.963

Reputation: 151

1

Befunge 98

"2+2".@

Remember that . is the way we print a number in Befunge.

Really not that interesting. First of all, it's pretty obvious that "2+2" is a string, not a number. And strings in Befunge simply push the elements onto the stack one at a time. So this clearly means that there is an ENQ character (ASCII 5) hiding after the last 2.

Justin

Posted 2014-05-30T06:54:35.963

Reputation: 19 757

1

Python

It's legit, I swear!

eval=len
print eval("2 + 2")

ɐɔıʇǝɥʇuʎs

Posted 2014-05-30T06:54:35.963

Reputation: 4 449

1

Ocaml

let p x f y = f x y + 1;;
print_int (p 2 (+) 2);;

Gary Drocella

Posted 2014-05-30T06:54:35.963

Reputation: 131

1

Apple Swift

extension Int {
     var add2:Int {return 5}
}
println(2.add2);

Maybe not the most clever one, but I like how it would look totally harmless if the extension was hidden in some library/header.

Losiowaty

Posted 2014-05-30T06:54:35.963

Reputation: 121

1

JavaScript

var a = 2;
var b = 0.1 + 0.2; // 0.3
b = Math.ceil(b * 10.0); // 3
b--; // 2
console.log(a + b);

Output: 5

wolfhammer

Posted 2014-05-30T06:54:35.963

Reputation: 1 219

1

T-SQL

--Set up a table to sum from
CREATE TABLE A (
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    VAL INT NOT NULL DEFAULT 1
    );

--Insert sum values to sum
BEGIN TRANSACTION A
INSERT INTO A (VAL) Values (2)
SAVE TRANSACTION A

BEGIN TRANSACTION B
    INSERT INTO A (VAL) Values (1)
    SAVE TRANSACTION B

    BEGIN TRANSACTION C
        INSERT INTO A (VAL) Values (4)
        SAVE TRANSACTION C
    ROLLBACK TRANSACTION C -- Get rid of last insert
ROLLBACK TRANSACTION B -- Get rid of the previous insert

INSERT INTO A (VAL) Values (2) -- Make sure we have another 2 in the table
SAVE TRANSACTION A 
COMMIT TRANSACTION A  -- Commit the transaction
GO 

-- Sum the table and format it nicely for the output using CONCAT
-- There is only two values so ordering for the first and last val not required
SELECT TOP 1 CONCAT(
    FIRST_VALUE(VAL) OVER (ORDER BY (SELECT NULL)),
    ' + ',
    LAST_VALUE(VAL) OVER (ORDER BY (SELECT NULL)),
    ' = ',
     SUM(VAL) OVER (ORDER BY (SELECT NULL))) AS VAL
FROM A;
/*
Result is output "2 + 2 = 5"
*/
DROP TABLE A;

Probably not that underhanded,but trying to take advantage over confusing nested transactions. Rollbacks only go back to the save point, not the beginning of the transaction.
ROLLBACK TRANSACTION C doesn't affect the table
ROLLBACK TRANSACTION B will roll back to SAVE TRANSACTION B removing the VAL 4 but not 1
As a matter of interest, if the (SELECT NULL) in the OVER clause is replaced with ID in the query the result ends up being 2 + 2 = 2

MickyT

Posted 2014-05-30T06:54:35.963

Reputation: 11 735

1

Java

How about this,

public class Simple 
{
    public static void main(String[] args) 
    {
        int x = 2;
        x += ++x;
        System.out.println(x);
    }
}

output: 5

Kruise

Posted 2014-05-30T06:54:35.963

Reputation: 29

Good idea, simple it is! – Timtech – 2015-02-11T11:59:13.227

Not really underhanded, since the ++x looks questionable. – BobTheAwesome – 2015-03-15T00:00:02.073

1

><>

02+02=05?v"Not 5"5[r]ooooo;
         >"5"o;

Outputs "5". How it works:

In ><>, each operation is one character, so if you were really finding 2 + 2, you would write 22+, for pushing 2, pushing 2 again and adding. The ? instruction does the following instruction only if a value popped off the stack is non-zero. The last value I push before using it is a 5, not a 0, so the branch to print "5" is executed. The stack at the end is [2 0 0]; 0 + 2 and 0 = 2 (booleans are 1 and 0), as well as the other 0 pushed.

bcsb1001

Posted 2014-05-30T06:54:35.963

Reputation: 450

1

C++

This uses some new techniques and some that have been already posted in conjunction with some new ones that have not.

METHOD 1

Using #define to override the primitive type with a custom type, and overriding the cast operator of the custom type to offset the value. Requires an intermediate variable of the custom type (scroll right). Works with cout, but printf avoids the cast operator and so it still returns 4. The printf line compiles in GCC 4.8, gives a warning in Clang with -std=c++11, and gives an error in Clang with -std=c++98.

                                                                                                                                                                                                                                                            struct Double { double x; Double(int x_) : x(x_) {} Double operator+(const Double& b) { return Double(x + b.x); } operator double() const { return x + 1; } };
#include <iostream>
#include <stdio.h>
                                                                                                                                                                                                                                                            #define double Double
int main() {
    double _2 = 2;
    std::cout << _2 + _2 << std::endl;
    printf("%f\n", _2 + _2);
}

METHOD 2

Using #define to override the primitive type with a custom type, and overriding the plus operator of the custom type. Requires an intermediate variable of a custom type. This method works with printf as well.

                                                                                                                                                                                                                                                            struct Double { double x; Double(int x_) : x(x_) {} double operator+(const Double& b) { return x + b.x + 1; } };
#include <iostream>
#include <stdio.h>
                                                                                                                                                                                                                                                            #define double Double
int main() {
    double _2 = 2;
    std::cout << _2 + _2 << std::endl;
    printf("%f\n", _2 + _2);
}

METHOD 3

Overshadowing namespaces. Works with any literal numbers, but only within the provided namespace.

#include <stdio.h>
#include <iostream>
                                                                                                                                                                                                                                                            namespace foo { namespace std { struct cout_ { ::std::ostream& operator<<(int x) { return ::std::cout << x+1; } } cout; using ::std::endl; } void printf(const char*, int) { ::printf("5\n"); } }
namespace foo {
void bar() {
    std::cout << 2 + 2 << std::endl;
    printf("%d\n", 2 + 2);
}
}

int main() { 
    foo::bar(); 
}

thenumbernine

Posted 2014-05-30T06:54:35.963

Reputation: 341

1

C++

#include <iostream>
#define TWO false ? 5 : 2
int main() {
    std::cout<< TWO << "+" << TWO << "=" << TWO+TWO;
    return 0;
}

Output:

2+2=5

How it works:

(false ? 5 : 2 + false ? 5 : 2) is the same as (false ? 5 : (2 + false ? 5 : 2)). (2 + false) is true.

Lucas

Posted 2014-05-30T06:54:35.963

Reputation: 665

1

Lua:

setmetatable(_G, {
    __newindex = function(t, i)
       rawset(t, i, setmetatable({}, {
            __add = function()
               return 5
            end
       }))
    end
})

a = 2
b = 2

print(a + b) -- 5

Try it

Trebuchette

Posted 2014-05-30T06:54:35.963

Reputation: 1 692

1

C

I haven't seen, among top three C solutions, the most obvious way to go. So, here it is.

#include <stdio.h>

#define a a=5,b

int main(void)
{
    int a = 2 + 2;
    printf("%d\n", a);
    return 0;
}

Of course this solution doesn't hide the trick to anyone with a eye. Moreover, one can argue that the extra argument in the printf may cause problems (even at compile time, depending on how you compile).

ShinTakezou

Posted 2014-05-30T06:54:35.963

Reputation: 131

1

Hassium

Not the most creative but here goes:

func main () {
    two = 2.5;
    five = two + two;
    println("two + two = " + five);
}

Run code online

Jacob Misirian

Posted 2014-05-30T06:54:35.963

Reputation: 737

4Wow... two=2.5 – ev3commander – 2015-10-29T21:34:25.667

1

Python 2

Here's another python one.

import sys

class Stdout(object):
    def __init__(self, target):
        self.target = target    
    def write(self, string):
        self.target.write("5")
sys.stdout = Stdout(sys.stdout)

print 2 + 2

This overwrites the stdout with a class that always returns 5. Pretty clever, eh?

TheInitializer

Posted 2014-05-30T06:54:35.963

Reputation: 829

1

Swift

Swift allows for custom operators, this one still lets any other two numbers be added as you'd expect but if both arguments are 2 it will return 5.

func +(l:Int, r:Int) -> Int {
    var a = -r - l
    if l == 2 && r == 2 {--a}
    return -a 
}

print(2+2)

Blake Lockley

Posted 2014-05-30T06:54:35.963

Reputation: 637

1

Python 2 (and maybe 3?)

import sys
def gettwo():
    global x,y
    y-=1                                  #Reduce global y back to 2
    x=2                                   #Set global x to 2
    sys.stdout.write("%d+%d="%(y,x))      #show the values we're going to be adding
    return x

y=3                                       #we'll reduce it to two in the gettwo() function
y+=gettwo()                               #y is now 2 and gets incremented by the 2 
                                          #returned from the function
sys.stdout.write(str(y))

Run this and it outputs:

2+2=5

I had a bug based on this crop up recently and it took me several minutes to figure out why it was happening. If you've never seen it before, it could be quite frustrating.

Python's operator assignment does things in a particular order. a+=b() is not the same as a=a+b(). It's more like =a;a=+b(). So, in this code the y-=1 ends up having no effect, as it is immediately overwritten by the remembered value of y when the function returns.

quintopia

Posted 2014-05-30T06:54:35.963

Reputation: 3 899

1

Mouse-2002

Mouse is a language about mathematical equation solving.

Every program starts with a letter declaring its name, here I've chosen a.

The ! exclamation point operator is not, as one might initially think, factorial; instead it "asserts" the immediately preceding equation and prints the equation's simpler side if the equation is true, in this case 5.

This is a very simple way to show that 2 + 2is 5.

a 2 + 2 = 5 !
> 5

Actually, Mouse is a very minimal stack-based language that uses Reverse Polish Notation (Postfix Notation), not infix.
The program a 2 + 2 = 5 ! actually pushes a's address (always 0), then adds 2 to that, then pushes 2 and pushes 1 if 0 + 2 is equal to 2 (which of course it is). Then, 5 is put on the top of the stack and the ! prints the top of the stack: magic.

cat

Posted 2014-05-30T06:54:35.963

Reputation: 4 989

1

Python 3

>>> import ctypes
>>> ctypes.cast(id(4),ctypes.POINTER(ctypes.c_int))[6]=5
>>> print(2 + 2)
5

You could do the same thing in a tuple or something if you didn't want it to be as obvious:

>>> import ctypes
>>> a = (-1, 2, 3)
>>> ctypes.cast(id(sum(a)),ctypes.POINTER(ctypes.c_int))[6]=5
>>> print(2 + 2)
5

Or just obfuscate it completely:

>>> from ctypes import*
>>> cast(id((8).bit_length()),POINTER(c_int))[6]=5
>>> print(2 + 2)
5

Unlike the other Python answer, this doesn't cause a segmentation fault (at least, for me).


Note (1): This will always show 5 as being the result of any of the following (and infinitely more)

  • 2 * 2
  • 5 - 1
  • -7 + 11

Note (2): It will also cause mishaps with division and such operations

  • 76 / 4 will result in 15.2 (which is actually the result of 76 / 5)
  • 4 * 9 will result in 45
  • range(4) will result in a range(0, 5)

Note (3): An OSError will be thrown when the result of a division or exponential expression is passed

  • 76 / 19
  • pow(3, 4)
  • 1 / 4

The answer will be returned but an OSError will also be thrown. Here's an example:

>>> print(1 / 4)
0.2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: raw write() returned invalid length 5 (should have been between 0 and 4)
0.2

This is not always the case, but more often than not, that is the result. The flip side would be this:

>>> print(1 / 4)
4.0
0.2

Zach Gates

Posted 2014-05-30T06:54:35.963

Reputation: 6 152

In Python 2, index the cast with 4, not 6. – Zach Gates – 2016-01-05T14:43:10.453

1Ooh, I like this. I'm gonna use this in production, for obfuscation's sake! – cat – 2016-01-05T16:33:49.563

Interestingly, print(ctypes.cast(id(4),ctypes.POINTER(ctypes.c_int))[6]) does cause a segfault. – cat – 2016-01-05T16:35:53.717

1

Retina

<empty>
2+2=?
.

Try it online!

Explanation

<empty>\n2+2=4 essentially passes the "string" 2+2=4 to the next regex. . outputs the number of matches (chars in this case), which is 5.

Mama Fun Roll

Posted 2014-05-30T06:54:35.963

Reputation: 7 234

1

CJam

X(2+2)+0;

Doesn't look like CJam? Think again.

Explanation

X(        e# push (X=1) decremented to stack [0]
  2       e# push 2 to stack                 [0 2]
   +      e# add                             [2]
    2)    e# push 2 incremented to stack     [2 3]
      +   e# add                             [5]
       0  e# push 0                          [5 0]
        ; e# pop and discard                 [5]
          e# implicit stack output

Mama Fun Roll

Posted 2014-05-30T06:54:35.963

Reputation: 7 234

1

PowerShell

$c=2                                                   # Set variable = 2
Write-Host ("$c + $c = " + $(2+($c++,$c--)[$c-eq2]))   # Perform the addition and output
Write-Host ("c = $c")                                  # Show that $c is still = 2

Output:

PS C:\Tools\Scripts\golfing> .\2-plus-2.ps1
2 + 2 = 5
c = 2

What the deuce?

Hint 1:

First, understand that the code (a, b)[c] (replacing a,b,c for values/variables) is a pseudo-ternary in PowerShell, where the dynamic array (a, b) is indexed into based on the value c.

Hint 2:

Next, understand that $true = 1 and $false = 0 and that arrays are zero-indexed. Thus, depending upon whether $c-eq2 ("$c is equal to 2") is True or False, we'll choose either the second or first value, respectively, and add that on to the 2.

Hint 3:

The dynamic array gets calculated before indexing.

Explanation:

The increment and decrement don't get evaluated twice. Instead, they're evaluated before the rest of the expression. Since we're creating a dynamic array, the first element of the array is processed as $c and saved as 2, and then the post-increment happens and sets $c=$c+1=3. The second element is processed as $c and saved as 3 (since $c was just set to 3), and then post-decremented back to 2. This makes our array (2,3). We index into that with $c-eq2 ... well, $c is now 2 again, so that evaluates to $true, or 1, and so selects the second element of the array, 3. Thus 2+3=5. And, since $c was decremented back down, we get the bonus of being able to output c = 2 still.

AdmBorkBork

Posted 2014-05-30T06:54:35.963

Reputation: 41 581

0

F#

let plus a b =
    match (a, b) with
    | (2, 2) -> 5
    | _ -> a + b

Alexan

Posted 2014-05-30T06:54:35.963

Reputation: 101

0

C

Is this too obvious?

#include <stdio.h>
int main()
{
int a=2,b=2,i=0;
int n=a+b;
for(;i<=n;++i){}
printf("%d\n",i);
getchar();
return 0;
}

JavaScript

alert("2 + 2".length);

bacchusbeale

Posted 2014-05-30T06:54:35.963

Reputation: 1 235

1It's not very well hidden to me... – user12205 – 2014-05-31T23:17:42.410

1Yeah, too obvious. C is capable of being far more cryptic. – ClickRick – 2014-06-01T14:22:38.283

0

Scheme (R7RS/R6RS)

#!r7rs            ; or #!r6rs
(import (scheme)) ; or (import (rnrs))

(define (dec x)
  (- x l))

(define (inc x)
  (+ x 1))

(define (peano+ a b)
  (if (>= a 1)
      (peano+ (dec a) (inc b))
      b))

(define l 1/2)
(define i 3/2)
(define f 5/2)
(define e 87/32)

(display (peano+ 2 2))
(newline)

How it works:

In the dec procedure i reduce by lower case L, which is a free variable. I define it lower down to be 1/2.(an exact number in Scheme) So my peano arithemtic procedure adds 1 to b but reduces a by 1/2 and since my base case does not stop at zero but everything below 1 (peano+ 2 2) ends up being 5.

Sylwester

Posted 2014-05-30T06:54:35.963

Reputation: 3 678

0

Clojure

(let [+a clojure.core/+]
  (intern 'clojure.core '+ (fn [& args] (if (= [2 2] args) 5 (apply +a args)))))

brendanb

Posted 2014-05-30T06:54:35.963

Reputation: 11

0

Java using unicode - this trick will probably work exactly the same in many other languages

For simplicity I will post 2 programs: The first one generates the second. The second one does the evil 2+2=5 but will be hard to read without the first one for context.

The generator:

import java . io . * ;

class main
{
    public static void main ( String [ ] args ) throws Exception
    {
    Writer writer = new FileWriter ( "stuff.java" ) ;
    writer . append ( "class stuff\n{\n\tpublic static void main ( String [ ] args )\n\t{\n\t\tint a\u00082=2; \n\t\tint b\u00082=3;\n\t\tSystem.out.println( a\u00082 + b\u00082  );\n\t}\n}" ) ;
    writer . close ( ) ;
    }
}

The evil program. It appears as below on my console.

class stuff
{
    public static void main ( String [ ] args )
    {
        int 2=2; 
        int 2=3;
        System.out.println( 2 + 2  );
    }
}

It outputs "5".

The trick:

I used control character for backspace \u0008 in the variable names. So my variable names are really "a backspace 2" and "b backspace 2" which are printed out on my console "2" and "2" respectively. When I examine the source code in my editor, they appear as "a^H2" and "b^H2".

emory

Posted 2014-05-30T06:54:35.963

Reputation: 989

0

Python 2

Yeah, not very original, but hey.

class int(int):__add__=lambda *a:5
print int(raw_input("Number? ")) + int(raw_input("Number? "))

int is still perfectly normal, except all additions return 5. Doesn't affect literals.

cjfaure

Posted 2014-05-30T06:54:35.963

Reputation: 4 213

0

template metaprogramming

#include <iostream>
#include <utility>
#include <type_traits>

enum class values {
  zero = 7,
  one = 3,
  two = 1,
  three = -7,
  four = 2,
  five = 4,
};

template<class T, T... ts> struct list {typedef list type;};
template<unsigned max, unsigned... ts> struct make_indexes:make_indexes<max-1, max-1, ts...>{};
template<unsigned... ts> struct make_indexes<0, ts...>:list<unsigned, ts...> {};
template<unsigned max> using make_indexes_t=typename make_indexes<max>::type;

template<class list> struct length_of;
template<class T, T... ts> struct length_of<list<T, ts...>>:std::integral_constant<unsigned, sizeof...(ts)> {};

template<class T, T t, class list> struct index_of;
template<class T, T t, T t0, T...ts> struct index_of<T, t, list<T, t0, ts...>>:
  std::integral_constant< unsigned, index_of<T, t, list<T, ts...>>::value+1 >
{};
template<class T, T t, T...ts> struct index_of<T, t, list<T, t, ts...>>:
  std::integral_constant< unsigned, 1 >
{};
template<class T, unsigned N, class list> struct value_at;
template<class T, unsigned N, T t0, T... ts> struct value_at<T, N, list<T, t0, ts...>>:value_at<T, N-1, list<T, ts...>> {};
template<class T, T t0, T... ts> struct value_at<T, 0, list<T, t0, ts...>>:std::integral_constant<T, t0> {};

template<class T> struct summable {};
template<> struct summable<values> {
  typedef values T;
  typedef list<T, T::zero, T::one, T::two, T::three, T::four, T::five> list_type;
  template<T t>
  using index = index_of< T, t, list_type >;
  template<unsigned N>
  using value = value_at< T, N, list_type >;
};

template<class T, template<T>class indexer>
unsigned index( T t, list<T> ) {
  return -1;
}

template<class T, template<T>class indexer, T t0, T... ts>
unsigned index( T t, list<T, t0, ts...> ) {
  if (t==t0)
    return indexer<t0>::value;
  else
    return index<T, indexer>( t, list<T, ts...>{} );
}

template<class T, template<unsigned>class valuer>
T value( unsigned N, list<unsigned> ) {
  return static_cast<T>(-1);
}
template<class T, template<unsigned>class valuer, unsigned M0, unsigned... Ms>
T value( unsigned N, list<unsigned, M0, Ms...> ) {
  if (N-1==M0)
    return valuer<M0>::value;
  else
    return value<T, valuer>( N, list<unsigned, Ms...>{} );
}


template<typename T>
T sum( T lhs, T rhs ) {
  typedef typename summable<T>::list_type list_type;
  return value<T, summable<T>::template value>( index<T, summable<T>::template index>(lhs, list_type{})+index<values, summable<T>::template index>(rhs, list_type{}), make_indexes_t<length_of<list_type>::value>{} );
}

template<typename T, typename=typename summable<T>::list_type >
T operator+( T lhs, T rhs ) {
  return sum( lhs, rhs );
}

all of which leads to this main:

int main() {
  auto two = values::two;
  auto five = values::five;
  std::cout << (two+two==five) << "\n";
  return 0;
}

which prints 1.

Mainly a game of misdirection. The enum values are not used anywhere in the code (so long as they are distinct). The template metaprogramming builds an entire infrastructure allowing positional-based addition of a list of values (regardless of their literal values) at compile time, and then a magic-switch construct converts this compile-time support to run-time support with sensible error messages. The indexes of elements are 1-based (so the first element is 1), and the reverse map does this properly. The only part where it fails is when we add together two elements: we add together their 1-based index. As two is in the 3rd position, we get the 6th position result, which is five.

Yakk

Posted 2014-05-30T06:54:35.963

Reputation: 859

1Are you sure there's not a shorter template strategy you could use? – Pharap – 2014-06-04T19:00:52.577

@Pharap I am certain there are many, many shorter template strategies I could have used! – Yakk – 2014-06-04T19:12:39.450

0

C++11

Kinda cheap, but whatever...

#include <iostream>

class mynumber
{
public:
    unsigned long long n;
    unsigned long long operator+(mynumber rhs)
    {
        return n + rhs.n + 1;
    }
};

constexpr mynumber operator"" _ (unsigned long long n)
{
    return mynumber{n};
}

int main()
{
    std::cout << "2 + 2 = " << 2_ + 2_;
}

chbaker0

Posted 2014-05-30T06:54:35.963

Reputation: 111

0

C

Tested on OS X Mavericks with /usr/bin/gcc (i.e. clang). Results will likely vary on different machines, compilers, libraries, etc...

main() {
    char buf[80];

    char fmt[] = "2 + 2 = \
    /* long long n requires 'll' prefix *\
    %lln";

    /* use a long long to avoid overflow in computing 2+2 */
    /* (that's typically how we get the wrong answer.) */
    long long n = 2;

    /* print out n + n, that is: 2 + 2 */
    sprintf(buf, fmt, &n + n);

    puts(buf);
}

Update: added Linux version:

#include <stdio.h>
main() {
    long long n = 2;
    char buf[80];
    sprintf(buf, "2 + 2 =\
        /* 'll' prefix for long long *\
        %lln\n", &n + n);
    puts(buf);
}

Output:

$ ./five 
2 + 2 = 5

Explanation:

The printf format %n is not a format specifier, it instead instructs printf to store the number of characters written so far in the int * argument parameter. The ll prefix tells printf that the argument is a long long pointer, thus 64-bits. The first comment "inline" in the string, is not actually a comment, but part of the format string, giving the entire format string enough padding that the %lln occurs at the 53 index---the ASCII code for '5'. The sprintf argument of '&n + n' points 8 characters into the format string. So sprintf writes the 64-bit value 53 to that offset in the buffer. On a little-endian intel that corresponds to the bytes {53, 0, 0, 0, 0, 0, 0, 0}, thus nicely zero-terminating our string so the "inline" comment is not also output with the puts. I ran out of ideas for obfuscating it further, the line continuation comment seemed a little better than alternatives I tried, but if anyone has suggestions, they're very welcome!

ɲeuroburɳ

Posted 2014-05-30T06:54:35.963

Reputation: 401

This is the output I have on 4.8.2-19ubuntu1 2 + 2 = /* long long n requires 'll' prefix *. Can you add the library you include and the compiling options? With -O1 -O2 -O3 it gives me *** %n in writable segment detected ***... core dump. Can you tell me if in your computer it functions my code?. Thanks

– Hastur – 2014-06-09T09:40:53.277

Thanks Hastur, I've updated my "solution" to include a linux version. Give it a shot. You should be able to compile it with just gcc -o five five.c. Just ignore any warnings, and don't add optimization flags. – ɲeuroburɳ – 2014-06-10T14:29:02.103

0

C/C++ cmath

The curse of the numbers below 473 and above 474...

#include <iostream>
#include <cmath>
#include <stdlib.h>

const int MaxA=5;
const int MaxB=5;
int A[] = {469,  470 , 471 ,472, 473};
int B[] = {474,  475 , 476 ,477, 478};

int Check_And_Calculate(int d, int c1,int c2){
 // It does a check on c1 and c2 and return the value of `-cubic root of c1^3` // 
 if (c1>c2) std::cerr << "# "<< c1 << " is **BIGGER** then " << c2 << std::endl;
     else   std::cerr << "# "<< c1 << " is NOT bigger then " << c2 << std::endl;
 return  -cbrt(c1*c1*c1)   ;
}

int main()
{
  int a=2, b=2;
  srand48(time(NULL));               // Random seed: Randomize the seed...
  int ValueA=A[int(MaxA*drand48())]; // It Extracts one random element from A
  int ValueB=B[int(MaxB*drand48())]; // It Extracts one random element from B

  a=a+Check_And_Calculate(a,ValueA,ValueB)+ValueB;  // It adds B subtracts A
  b=b+Check_And_Calculate(b,ValueB,ValueA)+ValueA;  // It adds A subtracts B

  std::cout << "2+2=" << a+b << "\n";
  return 0 ;
}

Output

# 473 is NOT bigger then 476
# 476 is **BIGGER** then 473 
2+2=5

Explanation

We could say that the A group are the good ones (at least this time) and the B ones are the Bad Guys. (They have a lot of friend! see below).
For some numbers we can observe the following behaviour for the cubic square root function, cbrt(x) and for the power one pow(x,1./3.)
3^3=27
pow(27.,1./3/)= 3.0000000000000004
15^3=3375
pow(3375.,1./3/)=14.999999999999998

When it is returned by an integer function it is made an automatic cast:
3.0000000000000004 becomes 3
14.999999999999998 becomes 14
So at the end it seems it was not a curse but only a problem of bad casting...

Notes:

The comparison in the function is needed (or some other code at least) else when it is compiled with -O1,-O2,-O3 option the code is substituted and the effect disappears.

The Wild Bunch
int MaxB=147;
B[]={15,27,30,37,54,60,67,71,74,108,117,119,120,134,139,142,148,161,191,205,216,221,225,229,234,237,238,239,240,253,268,278,284,296,315,322,382,407,410,417,431,432,439,441,442,443,445,449,450,458,465,468,474,475,476,477,478,480,481,487,501,505,506,527,536,551,556,563,567,568,592,593,630,641,644,743,751,764,775,791,801,814,820,829,834,857,861,862,864,867,878,879,882,884,886,890,898,900,903,905,907,915,916,923,925,927,929,930,936,947,948,950,952,954,955,956,957,960,962,967,971,974,975,983,1002,1010,1012,1017,1021,1027,1031,1054,1072,1102,1112,1126,1133,1134,1136,1181,1184,1186,1213,1249,1260,1279,1282}

Hastur

Posted 2014-05-30T06:54:35.963

Reputation: 277

Hi Hastur, I tried it out on OS X as you asked. It compiles fine, but gives 2+2=4! Something is incorrect about your incorrect math. :) – ɲeuroburɳ – 2014-06-10T14:35:53.943

0

A C++ template metaprogram:

#include <iostream>
#include <conio.h>

using namespace std;

template <int a, int b>
int add()
{
    return a + b;
}
template<>
int add<2, 2>()
{
    return 5;
}

int main()
{
    cout << "2 + 3 = " << add<2, 3>() << endl;
    cout << "2 + 2 = " << add<2, 2>();
    _getch();
}

The output will be:

2 + 3 = 5
2 + 2 = 5

wadf

Posted 2014-05-30T06:54:35.963

Reputation: 161

0

GolfScript

5:4;'"#{'"#{STDIN.gets}"-1<'}"'++~~

The program gets a line from STDIN, then evaluates it. Example run:

Input:

2 + 2

Output:

5

How it works:

The 5:4; assigns the value of 5 to 4. But simply computing 2 2+ would result in 4. So the rest of the program reads a line from STDIN, removes the trailing newline, then evaluates "#{line from stdin}" to let ruby add the numbers. So an input of 2 + 2 leaves a "4" on the stack. Lastly, we evaluate it again, resulting in 5.

Justin

Posted 2014-05-30T06:54:35.963

Reputation: 19 757

0

JavaScript

var two = {
    valueOf:function() { return 2; }, //two = 2
    toString:function() { return '3-1=2' } //interesting fact
}
var stringToPrint = '';
stringToPrint += "2 + 2 = " + two + two;
alert(stringToPrint);
alert("Oops, string concatenation instead of addition");
stringToPrint = '';
stringToPrint += "2 + 2 = " + (parseInt(two) + two); //convert a two to integer first
alert(stringToPrint); // 2 + 2 = 5 finally!

openorclose

Posted 2014-05-30T06:54:35.963

Reputation: 133

0

Mathcad

x:2
y:2
Given
x+y-4⎈=⎈!⎈!c
Find(x+y)=

Gives 5.

means the Ctrl key. It may not display properly in some browsers.

The trick is in the Given part. Given and everything that comes after it and before Find is called the Solve Block. The function Find will give the values of the variables which you pass to it which satisfy the equations inside the Solve Block, looping through the possible values of variables starting from their original values, in this case, x=2 and y=2. Here, the equation inside the Solve Block is x+y-4⎈=⎈!⎈!c, which gets formatted as x+y-4=¬¬c. Mathcad doesn't distinguish between scalars and booleans, just like ol' C89. And c is a built-in variable that stores an approximation of the speed of light in vacuum. So ¬¬c gives 1. This makes the equation x+y-4=1, and the only value of x+y that satisfies it is 5.

Mints97

Posted 2014-05-30T06:54:35.963

Reputation: 561

0

C (gcc-4.9.2, gcc-4.8.3 and probably other gcc compilers)

A different variant of a previously posted answer.

#include <stdio.h>

int main(void) {
    int i = 1;
    printf("%d\n", 
                ++i //++i returns 2, i is now 2
                + i++ //i++ returns i, i.e. 2
    );
    return 0;
}

(see it online here)

Same trick as https://codegolf.stackexchange.com/a/30138/36458, GCC actually evaluates them the other way around.

Mints97

Posted 2014-05-30T06:54:35.963

Reputation: 561

0

C#

I believe it works for .net framework <= 4.0

static void Main(string[] args)
    {
        Func<int, int> tmp = null;
        for (int i = 2; i < 3; i++)
            tmp = (x) => { return i + x; };
        Console.WriteLine(tmp(2));
    }

mike m

Posted 2014-05-30T06:54:35.963

Reputation: 41

0

PowerShell

#Make a character array string with the equation in it
#Measure the value, explicitly as a calculation
#Show only the resulting 'amount'
#(Golfed with short aliases and wildcard 'amount' for extra oomph)

[char[]]'2 + 2'|Measure -Sum|Select -Exp *t
5    

Nope, it measures the length of the string: 5 chars. It casts the string as char array, pipes those to Measure-Object; An array going into the pipeline is split into the contents, so there are five things to count. Measure-Object results in an object with these properties: {Count:5,Average: ,Sum:207, ...}. Then Select -Exp *t is a wildcard, but it matches the Count property instead of the non-existent 'Amount'; takes the value, and drops the rest. (-Sum is a thing, here adding up the ASCII character values, but I'm using it as a diversion)

TessellatingHeckler

Posted 2014-05-30T06:54:35.963

Reputation: 2 412

0

Python 2

yay operator overloading :P

class int:
    number = 2
    def __init__(self, number): 
        self.number = number
    def __add__(self, other):
        return self.number + other.number + 1

two = int(2)   # works without above def!
print two + two

try on ideone!

pretty simple to understand, just overwrites the int class with a new one that adds one to each addition thing. Seriously I'm surprised print 2+2 by itself doesn't work.

TheInitializer

Posted 2014-05-30T06:54:35.963

Reputation: 829

0

Vitsy

22+3mN
Since Vitsy is a stack language, it pushes 2 to the stack, 
then another 2, then adds them. Even so, it will do the following equation:
2+2=5

Output:

5

Visty may be stack based and 1D, but it can execute specific lines of a file (3m goes to the third line) What really happens here is 2+2, then push another 2 to the stack. Add the top two items, making the only item 6, pushes another 2, checks if the top two items are equal. If it's not (which it isn't), it pushes zero. Then, push 5 to the stack, and, finally, output the top item of the stack as a number.

Addison Crump

Posted 2014-05-30T06:54:35.963

Reputation: 10 763

0

PHP

var_dump(2 + 2 === (int)((0.1 + 0.7)*18.75/3) ? true : false);

Ok, before you say "wtf? Where is the 2+2=5 here?", bear with me:

0.1 + 0.7 = 0.8
0.8 * 18.75 = 15
15/3 = 5

And we all know that 5 = 5. So there is nothing wrong changing that, right? It should print false, right? Well... that's not the case. And here is the reason.

Clyff

Posted 2014-05-30T06:54:35.963

Reputation: 141

0

F#

let(+)_ _=5
2 + 2

There are other F# answers here, but I'm not sure why no one posted this one.

It simply redefines the result of addition operators to be the number 5.

Too obvious? A somewhat sneaker alternatively you would be:

let(~+)_=3
+ 2 + 2

It redefines the result prefix + to operator to be the number 3. The second + is normal addition. Note the space between the first + and the 2 is required to make the parser read it as an operator and not a literal; the other spaces are not required.

But this isn't underhanded enough. What about:

let printfn t 4=printfn t 5    
printfn "2 + 2 = %i" (2 + 2)

This doesn't change the actual result value of 2 + 2, it just changes what happens to get printed to the screen in output messages.

p.s.w.g

Posted 2014-05-30T06:54:35.963

Reputation: 573

0

TeaScript

\2+2=5\;
2+2

Outputs: 5


This also works:

\2+2=5\

Whaaat?


2+2=5? Sure, the TeaScript compiler just rolls with it
This feature is supposed to be used for golfing so you could do \p=n++\;p and that would compile to n++;n++. Essentially compile-time variables

Downgoat

Posted 2014-05-30T06:54:35.963

Reputation: 27 116

0

ngn/apl

+←=++

Reassigns X+Y to be a fork, viz. the sum of X=Y (which is 1 in the case of 2+2) and X+Y.

      +←=++
      2+2
5

Try it here.

Adám

Posted 2014-05-30T06:54:35.963

Reputation: 37 779

the sum of X=Y wat? – cat – 2016-03-23T01:49:12.393

0

Bash

alias +="printf'5\n'" 2+2=+ 2+=+ +2=+ 2=

After pasting/typing that in to your console, typing 2+2, 2 + 2, 2+ 2, and 2 +2 will all print 5 and a newline.

For more golfiness, alias 2+2="printf'5\n'" also works.

Rɪᴋᴇʀ

Posted 2014-05-30T06:54:35.963

Reputation: 7 410

-1

PHP

Here are 2 methods I found working

Method 1

echo (2+2 === '4' ? 4 : 5);

Method 2

$a = $b = 2;
echo ($a + ++$b);

c0de Freak

Posted 2014-05-30T06:54:35.963

Reputation: 55

-1

Python 2.7 a emotional answer to the problem

# Code and error numbers for all errors that can occur.
error_number = 53
error_descrption = "Error occured"

try:
    bird;
    """

    This is the lead motive of our application.
    This was made by jrei (http://www.chris.com/ascii/index.php?art=animals/birds%20(land))


                               _,---._      __,...-----...___
                           _,-:::,,--.`,--''                 `'--._
                         ,':::::/((##)):                           `-.
                       ,':.::::/  `--' :         _____.....______ (:::\
                      /:::::::/        :__,.-''''..- - - - --  -- .`_-:\
                     /:,:::.::|        ::.          ____....-----.....`.
                    /,:::::::/          ::::__.--'''
                    |:::::::|           _:'
                    |:.:::::|         ,'
                    |:::::::|         |
                   /::::.:::|         |
              __,-'::.::::::|         |
       _,.--''::::_::::::::::\        |
     ''::_::,:--''  `'--.:::::\       ;
     -'''::::::::::::::::\:::::`.     ;
     :::::::::::::::::::::|:.::::`-..-
     ::;::::::::::::::::::|::::::::::/
     :/::::::/::::::;:::::|::::.::::/
     (::::::/::::::/::::::):.::::::'
     :`:__,;::::::;:::::,':::::::'
     ,-':::`.__,-'::::,'::::::-'
     :::::,-'::::::,-':::_:-'
     _,-':::::::,-'::_:-'
     jrei::::,-_:--''
      ::,::--''



    I think it resembles our application the best.
    The strength and the speed of the bird are the same characteristics as our
    application. 


    So dear reader enough talk, now comes the code which makes the application so
    incredible! Buckle up your seatbelts! It will be a tough ride.




    """



    print "{}".format(2+2)



    """
    Oh dear reader i forgot to show you, how this program actually is structured.
    I think the best way is UML, because everybody loves it.

    +--------+       +---------------------+ *
    | Client |------>| Component           |<-------------------------+
    +--------+       +---------------------+                          |
                     | Operation()         |                          |
                     | Add(Component)      |                          |
                     | Remove(Component)   |                          |
                     | GetChild(int)       |                          |
                     +---------------------+                          |
                               #                                      |
                               |                                      |
                    +----------+--------------+                       |
                    |                         |                       |
                +------+------+   +----------+----------+  children   |
                | Leaf        |   | Composite           |O------------+
                +-------------+   +---------------------+
                | Operation() |   | Operation()         |
                +-------------+   | Add(Component)      |
                                  | Remove(Component)   |
                                  | GetChild(int)       |
                                  +---------------------+



    I especially want to say thank you to all people, which where part of this project.
    It took me several weeks to code this stuff and went through a hard time.
    My wife broke up with me and my dog died. I am a very emotional person,
    and this hit me really hard. But it is very nice, that i have somebody like you,
    someon i can talk to. I think this code is the fastest implementation on out there.
    I am very proud of it and it gives me the strength to go on with my life.
    Although i miss my wife, this is the past. I need to find a way to look into the future.
    I am a little bit overweight, but i do workouts to get fit.
    I try to avoid hotdogs, but they are just so jummy. But i will find the inner
    strength to avoid them.


    Thank you very much.
    Sincerely (insert name here)




    """
# Just some basic handling error in the case something goes wrong
# My Code is perfectly fine (insert link to xkcd comic here), but you never know
except NameError:
    try:
        print chr(error_number), error_description
    except NameError:
        pass

nvidia

Posted 2014-05-30T06:54:35.963

Reputation: 327

1Took me 30 seconds to see the error. – kirbyfan64sos – 2015-11-06T15:47:00.863

-2

Because we love to trust in the docstring and our debug decorators.

from functools import wraps

def debug(func):
    @wraps(func)
    def wrapper(*args):
        print "*DEBUG"
        print "**Calling help on %s" % func.__name__
        help(func)
        print "** Executing %s(a=%s,b=%s)" % (func.__name__,args[0],args[1])
        print "**%s + %s = " % (args[0], args[1]),
        return func(args[0] + 1, args[1])

    return wrapper

@debug
def Add(a=2, b=2):
    """
    :param a: default 2
    :type a: int
    :param b: default 2
    :type b: int
    :returns: a+b
    :rtype: int
    """
    return a + b

print Add(2, 2)

f.rodrigues

Posted 2014-05-30T06:54:35.963

Reputation: 645

1This is not hidden at all: return func(args[0] + 1, args[1]). – Kyle Kanos – 2014-07-17T14:56:22.413

It's a practical joke. Because we usually trust in the docstring and the debugger. If something like this happens deep down a big program, you don't have a simple way to track it down because the @wraps changes the 'wrapped' to the add(). – f.rodrigues – 2014-07-17T15:27:07.327

-2

C#

Console.WriteLine(" 2+2=".Length);

Miro

Posted 2014-05-30T06:54:35.963

Reputation: 1

9That doesn't really look like it should print 4, does it? ;) – Martin Ender – 2014-12-31T10:17:46.990

-3

Mathcad

Simply write it down using the boolean equality operator or define an another addition function using the + character ...

enter image description here

Stuart Bruff

Posted 2014-05-30T06:54:35.963

Reputation: 501

-4

C#

Didn't see anyone write this I think...

    static void Main(string[] args)
    {
        int two = 2;

        int answer = two + two;

        if (answer == 4)
        {
            answer++;
        }

        Console.WriteLine(two + " + " + two + " = " + answer);
        Console.ReadLine();
    }

kenevil1

Posted 2014-05-30T06:54:35.963

Reputation: 1

6This question is an [tag:underhanded] contest. Answers should appear that they will output 4, but in reality output 5. Your submission does not seem to be trying to hide the fact that it will output 5, so it may not be considered a very good answer for this question. Anyway, welcome to PPCG! :) – user12205 – 2014-05-31T21:49:47.127

Sorry everybody else took the good ones. :( – kenevil1 – 2014-06-01T09:20:03.163