Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
27  
This is question in book "1984" by George Orwelll. –  bacchusbeale May 30 at 12:23
57  
Why is this underhanded? Two plus two is five. –  Geobits May 30 at 16:23
41  
THERE! ARE! FOUR! LIGHTS! –  Nick T May 30 at 19:57
72  
@Geobits - I agree: 2+2=5 you can see it in this calculator. –  MT0 May 30 at 20:03
26  
echo "2+2=5"; –  Awal Garg May 31 at 12:16

96 Answers 96

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.

share|improve this answer
4  
Thought of this one as soon as I saw the question :) –  Kenzie Togami May 30 at 17:14
183  
That. Is. Evil. Absolutely evil. +1 –  Jan Dvorak May 30 at 17:45
31  
@JanDvorak in chat it was suggested Integer[] array = (Integer[]) c.get(cache); fisherYatesShuffle(array); Just imagine how many things would break... –  MichaelT May 30 at 17:57
11  
Answers like this make me love this site more than SO. –  Songo May 30 at 21:33
16  
zomg, java answers never get top votes! +1 for bringing java to the top :) –  Cruncher Jun 2 at 16:20

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.

share|improve this answer
50  
Scrollbar is visible in Chromium, but who pays attention to it at first? :) –  Ruslan May 31 at 17:56
101  
To 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 May 31 at 22:29
11  
In 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 Faulds Jun 1 at 12:15
28  
Clever, but on mobile it just wordwraps :) –  Logan Jun 1 at 18:42
8  
This is the only time that scrolling SE code windows don't make me want to break someone's fingers. –  ObscureRobot Jun 1 at 21:23

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
share|improve this answer
20  
What does let 2+2=5 in 5+5 do? ಠ_ಠ –  Jan Dvorak May 30 at 17:44
13  
@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 May 30 at 17:50
4  
The plus operator is a function, and let can redefine existing functions. let (+) 2 2 = 5 in (+) 2 2 –  SHiNKiROU May 30 at 18:31
21  
@SHiNKiROU shadow, not redefine –  Jan Dvorak May 30 at 18:33
50  
that almost sounds like: "And God said let 2+2=5 in 2+2" )) –  N0ir May 30 at 23:15

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.

share|improve this answer
8  
Those fonts look different though. Do you think you could make it use the correct font? –  Andrea Faulds Jun 1 at 12:18
    
@AndreaFaulds I'm using the emulator from 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. –  steveverrill Jun 1 at 18:05
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 Jun 1 at 20:55
    
This matches the original font in the BBC Micro: VDU 23,52,126,96,124,6,6,102,60,0 –  squeamish ossifrage Jun 2 at 10:37
    
@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. –  steveverrill Jun 2 at 10:46

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.

share|improve this answer
36  
Math.ceil(two + two); // round just in case I see what you did there –  Tim S. May 30 at 16:59
9  
Making both a function and a variable with the same name... Wow. –  configurator Jun 1 at 17:30
46  
@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 Jun 2 at 1:09
12  
Two.Infinity.And.Beyond() –  CincauHangus Jun 2 at 10:00
4  
+1 for the public service reminder to run far far away from Java. –  Caleb Jun 4 at 7:35

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.

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.

share|improve this answer
51  
Yes, we definitely all just casually ignore segfaults... –  professorfish May 31 at 11:20
6  
It's worth mentioning that this isn't really a Python trick and is only specific to the C implementation of Python. –  xApple Jun 2 at 0:05
13  
exec('\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 Jun 2 at 20:14
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 Jun 2 at 22:00
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 Jun 2 at 23:21

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.

share|improve this answer
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 May 31 at 8:39
52  
Using homoglyphs to "confuse" readers is now officially not funny. –  Jan Dvorak Jun 1 at 5:46
15  
The homoglyphs become funny in combination with javascript's ridiculous global variables. –  Konstantin Weitz Jun 1 at 17:16
3  
It's not the "Unicode Η character", it's Latin H and Greek Eta (Η). –  phyzome Jun 2 at 15:39
3  
@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 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? –  Jan Dvorak Jun 4 at 13:47

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

share|improve this answer
4  
Nice maths trick going on there! –  tomsmeding May 31 at 19:07
4  
@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 –  professorfish Jun 1 at 16:28
1  
Oh this is just fabulous. lmao –  Joe Harper Jun 3 at 10:00
2  
See 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)) –  Dennis Williamson Jun 9 at 21:29
1  
Nice one, but I spotted the += thing immediately. –  nyuszika7h Jul 2 at 8:41

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.

share|improve this answer

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

share|improve this answer
16  
obligatory phpsadness –  WChargin Jun 1 at 4:12
    
I've got another PHP example: $a=2;echo "2+2=".$a++ + $a++; –  avall Jun 1 at 21:27
    
It's obvious that $a++ makes 3 and the result will be 6. I don't get what you're thinking. –  Ozh Jun 2 at 9:58
    
excellent point :D –  Alireza Fallah Jun 2 at 12:19
1  

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

share|improve this answer
2  
I 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? –  professorfish May 30 at 18:29
2  
@professorfish Applescript, for example: set a to {1, 2, 3, 4, 5, 6, 7, 8} item 4 of a –  DigitalTrauma May 30 at 18:32
5  
@DigitalTrauma Applescript is weird –  professorfish May 30 at 18:44
4  
zsh 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 May 30 at 18:57
2  
@professorfush: Lua & Fortran are 1 indexed. Anytime I count to 10, I always start at 1, not 0. :D –  Kyle Kanos May 30 at 23:23

JavaScript

var total = 2 + 2;

if(total = 5)
{
    alert('I guess 2 + 2 = 5');
}
else
{
    alert('The universe is sane, 2 + 2 = 4');
}
share|improve this answer
44  
= instead of ==, easy to see and frankly rather uninspired. –  ValekHalfHeart May 30 at 20:06
12  
Have an upvote anyway, I make that mistake a lot –  professorfish May 31 at 10:51
2  
I still like this answer –  Sam Creamer Jun 2 at 17:43
1  
I like it too. Not every language uses = only as an assigment but a comparison operator (e.g. Pascal, SQL, VB) –  avall Jun 2 at 20:27

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.

share|improve this answer
9  
This is quite sly. Nobody ever looks at your imports/includes. –  professorfish May 31 at 13:51

C#

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

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

        Console.WriteLine(x + y);
    }
share|improve this answer
5  
ah, the good old trick with rogue characters. That's why you should use 1TBS everywhere. –  Jan Dvorak May 30 at 17:52
7  
@JanDvorak Does this work because of the semicolon after the if statement? I don't know C# but I have used C++ –  professorfish May 30 at 18:31
3  
@professorfish that's what I assume. Also, languages that don't let you insert random curly braces FTW. –  Jan Dvorak May 30 at 18:33
6  
Without 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. –  Grax May 30 at 18:58
1  
I 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. –  Mark Jun 2 at 0:32

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.

share|improve this answer
    
I don't know brainfuck, it took me a couple of minutes to figure this out. ASCII 53, right? –  steveverrill Jun 5 at 21:12
1  
As long you have the +++++. you can paint anything. –  Eduard Florinescu Jun 6 at 10:20
    
@steveverrill : yes you are right. (and this is the only way to output ascii characters in BF). –  tigrou Jun 6 at 11:32
1  
I was considering doing a brainfuck answer, this saved me the time. –  Pharap Jun 6 at 23:28

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.

share|improve this answer
    
Can you explain that for people who don't speak GolfScript please? –  MadTux Jun 10 at 9:42
    
@MadTux Here you go. –  eBusiness Jun 10 at 16:14
    
Thanks. (I'll upvote later because I reached my daily limit, here's a beer.) –  MadTux Jun 10 at 16:21
    
Simple and cheaty, I love it. +1 –  Sieg Jun 10 at 16:22

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(1,3) would all give the expected answer.

share|improve this answer
4  
Not bad, fooled me for a bit. –  qwr Jun 2 at 6:22

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.

share|improve this answer
5  
That's a very strange main signature. –  Bertie Wheen Jun 1 at 22:11
4  
Java implements variadic arguments as arrays under the hood. –  CodaFi Jun 2 at 4:47
1  
Took 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. –  Quincunx Jun 9 at 6:59

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

share|improve this answer
    
Why ~eval(`a`) instead of just ~a? –  Andrea Corbellini Jun 2 at 13:25
1  
I wanted to leave some of the int() functionality and eval() does the job if the input is a stringified integer :) –  avall Jun 2 at 14:27

Scheme

(define 2+2 5)
2+2 ;=> 5
share|improve this answer
7  
hey! 2+2 isn't how you do addition in lisp! –  Jan Dvorak May 30 at 17:54
1  
So what? It seemingly add 2 to 2 as is in the task. –  Łukasz Niemier May 30 at 18:33
69  
@JanDvorak I've never used lisp, but as I understand it it's something like ((((2))(()()))()()(()((((+))))()(((()(())((((2)))))()))(()))). –  undergroundmonorail May 31 at 4:00
1  
"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: pastebin.com/KHtm9Jmv –  Felipe Micaroni Lalli Jun 2 at 4:42
1  
@FelipeMicaroniLalli that adnotation was made after my answer so it doesn't count. –  Łukasz Niemier Jun 4 at 8:36

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.

share|improve this answer
5  
+1 for awakening a ghost of the past –  Jan Dvorak May 30 at 18:11
6  
@JanDvorak: Haha, I could have used FORTRAN IV in which I could redefine literals, e.g. 2=3 –  Kyle Kanos May 30 at 18:12
1  
@KyleKanos, that's what I thought this was going to be when I saw your post was written in FORTRAN. –  crazedgremlin May 30 at 21:56
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 Jun 3 at 19:08
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 Jun 3 at 19:23

F#

Let's put in fsi following statement:

let ``2+2``= 5

Output:

val ( 2+2 ) : int = 5
share|improve this answer

JavaScript

Code:

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

Output:

5

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

share|improve this answer
5  
Can 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 May 30 at 23:14
13  
the "a" variable isnt the same both times (sorry if im spoiling this). Sneaky unicode indeed –  Sam Creamer May 31 at 2:16
2  
I love how the next character, U+0431, is б—almost 6! –  WChargin Jun 1 at 4:12
26  
Using homoglyphs to "confuse" readers is now officially not funny. –  Jan Dvorak Jun 1 at 5:56
8  
@JanDvorak That answer was posted after this one; it doesn't apply here. –  Doorknob Jun 1 at 12:26

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.

share|improve this answer
    
Also: class Fixnum; def +(n) 5 end end; 2 + 2 # => 5 –  film42 Jun 2 at 2:38
    
To 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 Jun 5 at 3:26

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.

share|improve this answer
    
The second program produces an infinite loop for me. See here –  Anant Jun 7 at 13:15
    
@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 Jun 7 at 14:52
    
Ah okay, thanks! –  Anant Jun 7 at 15:45

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.

share|improve this answer
4  
A range starting and ending at 2 would be just { 2 }, wouldn't it? –  Paŭlo Ebermann May 31 at 22:12
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 Jun 1 at 0:21
9  
@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 Jun 1 at 0:29
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 Jun 2 at 13:38

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.

share|improve this answer
    
Nice; I can't upvote if undefined behavior isn't allowed. –  this Jun 1 at 13:27
1  
@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 Jun 1 at 14:18
1  
I 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 Jun 1 at 19:27

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.

share|improve this answer
2  
Nice use of unspecified behavior –  mebob Jun 5 at 0:34

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.

share|improve this answer

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!

share|improve this answer
1  
Same answer I was going to post. Because operator overloading is evil in so many cases! :) –  Mike McMahon Jun 2 at 5:25
1  
And good in so many other! :D –  NaCl Jun 2 at 15:38

protected by Community Jun 1 at 3:03

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

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

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