# Write a program that makes 2 + 2 = 5 [closed]

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.

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

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

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

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

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

• What does let 2+2=5 in 5+5 do? ಠ_ಠ – John Dvorak May 30 '14 at 17:44
• @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 '14 at 17:50
• @SHiNKiROU shadow, not redefine – John Dvorak May 30 '14 at 18:33
• that almost sounds like: "And God said let 2+2=5 in 2+2" )) – OutFall May 30 '14 at 23:15
• @user3217013 Learn Haskell, it's good for your heart. – Shoe Jun 2 '14 at 2:19

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

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

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

• Can you explain that for people who don't speak GolfScript please? – MadTux Jun 10 '14 at 9:42
• @MadTux Here you go. – aaaaaaaaaaaa Jun 10 '14 at 16:14
• Thanks. (I'll upvote later because I reached my daily limit, here's a beer.) – MadTux Jun 10 '14 at 16:21
• Simple and cheaty, I love it. +1 – seequ Jun 10 '14 at 16:22
• i like it becaus it doesn't seem like it's tricking you with math or semantics, it seems so straightforward and yet 5 ^^ – dwana Dec 26 '14 at 10:44

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

• Math.ceil(two + two); // round just in case I see what you did there – Tim S. May 30 '14 at 16:59
• Making both a function and a variable with the same name... Wow. – configurator Jun 1 '14 at 17:30
• @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 '14 at 1:09
• Two.Infinity.And.Beyond() – CincauHangus Jun 2 '14 at 10:00
• @TimS I ceil what you did there – thenaglecode Jul 11 '14 at 4:10

# 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


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.

• Those fonts look different though. Do you think you could make it use the correct font? – Andrea Jun 1 '14 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. – Level River St Jun 1 '14 at 18:05
• @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 '14 at 20:55
• This matches the original font in the BBC Micro: VDU 23,52,126,96,124,6,6,102,60,0 – r3mainer Jun 2 '14 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. – Level River St Jun 2 '14 at 10:46

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

• I don't know brainfuck, it took me a couple of minutes to figure this out. ASCII 53, right? – Level River St Jun 5 '14 at 21:12
• As long you have the +++++. you can paint anything. – Eduard Florinescu Jun 6 '14 at 10:20
• @steveverrill : yes you are right. (and this is the only way to output ascii characters in BF). – tigrou Jun 6 '14 at 11:32
• I don't understaaaand – Leif Willerts Oct 29 '15 at 21:54

# 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

• Nice maths trick going on there! – tomsmeding May 31 '14 at 19:07
• @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 – user16402 Jun 1 '14 at 16:28
• 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)) – Paused until further notice. Jun 9 '14 at 21:29
• Nice one, but I spotted the += thing immediately. – nyuszika7h Jul 2 '14 at 8:41
• @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 – user16402 Jul 24 '14 at 7:11

# Python

>>> patch = '\x312\x2D7'
>>> 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_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):

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. • Yes, we definitely all just casually ignore segfaults... – user16402 May 31 '14 at 11:20 • 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 '14 at 0:05 • @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 Jun 2 '14 at 19:12 • 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 '14 at 20:14
• 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 '14 at 23:21

# JavaScript:

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

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

// 3 + 3 = 6
// 2 + 2 = 5


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.

• @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 '14 at 8:39
• Using homoglyphs to "confuse" readers is now officially not funny. – John Dvorak Jun 1 '14 at 5:46
• The homoglyphs become funny in combination with javascript's ridiculous global variables. – Konstantin Weitz Jun 1 '14 at 17:16
• It's not the "Unicode Η character", it's Latin H and Greek Eta (Η). – treat your mods well Jun 2 '14 at 15:39
• @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? – John Dvorak Jun 4 '14 at 13:47

# JavaScript

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



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.

• Well it's actually more like 5.01 decibels, but far away enough from 4 to count. – Joe Z. Jan 12 '16 at 20:57

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

• obligatory phpsadness – wchargin Jun 1 '14 at 4:12
• I've got another PHP example: $a=2;echo "2+2=".$a++ + $a++; – avall Jun 1 '14 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 '14 at 9:58
• @Janus PHPsadness #30 explains it well – wchargin Jun 3 '14 at 4:13
• Also trending on stackexchange... – recursion.ninja Jun 4 '14 at 15:26

### JavaScript

var total = 2 + 2;

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

• = instead of ==, easy to see and frankly rather uninspired. – ApproachingDarknessFish May 30 '14 at 20:06
• Have an upvote anyway, I make that mistake a lot – user16402 May 31 '14 at 10:51
• I still like this answer – Sam Creamer Jun 2 '14 at 17:43
• I like it too. Not every language uses = only as an assigment but a comparison operator (e.g. Pascal, SQL, VB) – avall Jun 2 '14 at 20:27
• I find it very obvious – Oliver Ni Jan 1 '15 at 23:14

# C#

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

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

Console.WriteLine(x + y);
}

• ah, the good old trick with rogue characters. That's why you should use 1TBS everywhere. – John Dvorak May 30 '14 at 17:52
• @JanDvorak Does this work because of the semicolon after the if statement? I don't know C# but I have used C++ – user16402 May 30 '14 at 18:31
• @professorfish that's what I assume. Also, languages that don't let you insert random curly braces FTW. – John Dvorak May 30 '14 at 18:33
• 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. – Grax32 May 30 '14 at 18:58
• 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. – mpen Jun 2 '14 at 0:32

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

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

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

• I 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 Apr 9 '15 at 1:51

# Bash

#!/bin/bash

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

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

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

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

• This is quite sly. Nobody ever looks at your imports/includes. – user16402 May 31 '14 at 13:51

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

• Not bad, fooled me for a bit. – qwr Jun 2 '14 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.

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

## Befunge

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

#>>>>>>>>>>>>>>>>>v
# Calculate 2 + 2 v
#>>>>>>>>>>>>>>>>>v
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.

• +1, This is very devious, because who the hell looks at the program that runs the source code when debugging? – MrLore Jul 25 '14 at 3:45

JavaScript

Code:

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


Output:

5


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

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

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

• Nice use of unspecified behavior – chbaker0 Jun 5 '14 at 0:34

## FORTRAN 77

       program BadSum
integer i,a,j
common i,a
a = 1
i = 2
print *,j
end

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.

• @JanDvorak: Haha, I could have used FORTRAN IV in which I could redefine literals, e.g. 2=3 – Kyle Kanos May 30 '14 at 18:12
• @KyleKanos, that's what I thought this was going to be when I saw your post was written in FORTRAN. – danmcardle May 30 '14 at 21:56
• @KyleKanos Do it! – ClickRick Jun 1 '14 at 3:10
• @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 '14 at 19:08
• @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 '14 at 19:23

## Python

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

return int(a)+int(b)



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

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


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

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

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

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

• Also: class Fixnum; def +(n) 5 end end; 2 + 2 # => 5 – film42 Jun 2 '14 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 '14 at 3:26

# Scheme

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

• hey! 2+2 isn't how you do addition in lisp! – John Dvorak May 30 '14 at 17:54
• So what? It seemingly add 2 to 2 as is in the task. – Hauleth May 30 '14 at 18:33
• @JanDvorak I've never used lisp, but as I understand it it's something like ((((2))(()()))()()(()((((+))))()(((()(())((((2)))))()))(()))). – undergroundmonorail May 31 '14 at 4:00
• "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 Jun 2 '14 at 4:42
• @FelipeMicaroniLalli that adnotation was made after my answer so it doesn't count. – Hauleth Jun 4 '14 at 8:36

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

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

# F#

Let's put in fsi following statement:

let 2+2= 5


Output:

val ( 2+2 ) : int = 5


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

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