391
votes
\$\begingroup\$

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.

\$\endgroup\$
23
  • 48
    \$\begingroup\$ This is question in book "1984" by George Orwelll. \$\endgroup\$ May 30, 2014 at 12:23
  • 97
    \$\begingroup\$ Why is this underhanded? Two plus two is five. \$\endgroup\$
    – Geobits
    May 30, 2014 at 16:23
  • 79
    \$\begingroup\$ THERE! ARE! FOUR! LIGHTS! \$\endgroup\$
    – Nick T
    May 30, 2014 at 19:57
  • 105
    \$\begingroup\$ @Geobits - I agree: 2+2=5 you can see it in this calculator. \$\endgroup\$
    – MT0
    May 30, 2014 at 20:03
  • 47
    \$\begingroup\$ echo "2+2=5"; \$\endgroup\$ May 31, 2014 at 12:16

156 Answers 156

1
2 3 4 5 6
665
votes
\$\begingroup\$

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.

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

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.

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

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
\$\endgroup\$
19
  • 36
    \$\begingroup\$ What does let 2+2=5 in 5+5 do? ಠ_ಠ \$\endgroup\$ May 30, 2014 at 17:44
  • 22
    \$\begingroup\$ @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. \$\endgroup\$
    – Flonk
    May 30, 2014 at 17:50
  • 27
    \$\begingroup\$ @SHiNKiROU shadow, not redefine \$\endgroup\$ May 30, 2014 at 18:33
  • 96
    \$\begingroup\$ that almost sounds like: "And God said let 2+2=5 in 2+2" )) \$\endgroup\$
    – OutFall
    May 30, 2014 at 23:15
  • 11
    \$\begingroup\$ @user3217013 Learn Haskell, it's good for your heart. \$\endgroup\$
    – Shoe
    Jun 2, 2014 at 2:19
183
votes
\$\begingroup\$

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.

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

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.

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

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.

\$\endgroup\$
10
  • 8
    \$\begingroup\$ Those fonts look different though. Do you think you could make it use the correct font? \$\endgroup\$
    – mystery
    Jun 1, 2014 at 12:18
  • \$\begingroup\$ @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. \$\endgroup\$ Jun 1, 2014 at 18:05
  • 5
    \$\begingroup\$ @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' \$\endgroup\$ Jun 1, 2014 at 20:55
  • 1
    \$\begingroup\$ This matches the original font in the BBC Micro: VDU 23,52,126,96,124,6,6,102,60,0 \$\endgroup\$
    – r3mainer
    Jun 2, 2014 at 10:37
  • \$\begingroup\$ @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. \$\endgroup\$ Jun 2, 2014 at 10:46
131
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ I don't know brainfuck, it took me a couple of minutes to figure this out. ASCII 53, right? \$\endgroup\$ Jun 5, 2014 at 21:12
  • 4
    \$\begingroup\$ As long you have the +++++. you can paint anything. \$\endgroup\$ Jun 6, 2014 at 10:20
  • 1
    \$\begingroup\$ @steveverrill : yes you are right. (and this is the only way to output ascii characters in BF). \$\endgroup\$
    – tigrou
    Jun 6, 2014 at 11:32
  • 1
    \$\begingroup\$ I don't understaaaand \$\endgroup\$ Oct 29, 2015 at 21:54
105
votes
\$\begingroup\$

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

\$\endgroup\$
8
  • 8
    \$\begingroup\$ Nice maths trick going on there! \$\endgroup\$
    – tomsmeding
    May 31, 2014 at 19:07
  • 5
    \$\begingroup\$ @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 \$\endgroup\$
    – user16402
    Jun 1, 2014 at 16:28
  • 2
    \$\begingroup\$ 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)) \$\endgroup\$ Jun 9, 2014 at 21:29
  • 2
    \$\begingroup\$ Nice one, but I spotted the += thing immediately. \$\endgroup\$ Jul 2, 2014 at 8:41
  • 2
    \$\begingroup\$ @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 \$\endgroup\$
    – user16402
    Jul 24, 2014 at 7:11
101
votes
\$\begingroup\$

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.

\$\endgroup\$
15
  • 96
    \$\begingroup\$ Yes, we definitely all just casually ignore segfaults... \$\endgroup\$
    – user16402
    May 31, 2014 at 11:20
  • 10
    \$\begingroup\$ It's worth mentioning that this isn't really a Python trick and is only specific to the C implementation of Python. \$\endgroup\$
    – xApple
    Jun 2, 2014 at 0:05
  • 1
    \$\begingroup\$ @NickT Ah! okay. I was under the impression that you had tried the original under the same 64-bit windows, 32-bit ubuntu setup \$\endgroup\$ Jun 2, 2014 at 19:12
  • 22
    \$\begingroup\$ 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. \$\endgroup\$ Jun 2, 2014 at 20:14
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Jun 2, 2014 at 23:21
86
votes
\$\begingroup\$

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.

\$\endgroup\$
19
  • 4
    \$\begingroup\$ @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. \$\endgroup\$
    – d3dave
    May 31, 2014 at 8:39
  • 79
    \$\begingroup\$ Using homoglyphs to "confuse" readers is now officially not funny. \$\endgroup\$ Jun 1, 2014 at 5:46
  • 29
    \$\begingroup\$ The homoglyphs become funny in combination with javascript's ridiculous global variables. \$\endgroup\$ Jun 1, 2014 at 17:16
  • 3
    \$\begingroup\$ It's not the "Unicode Η character", it's Latin H and Greek Eta (Η). \$\endgroup\$ Jun 2, 2014 at 15:39
  • 4
    \$\begingroup\$ @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? \$\endgroup\$ Jun 4, 2014 at 13:47
71
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Well it's actually more like 5.01 decibels, but far away enough from 4 to count. \$\endgroup\$
    – Joe Z.
    Jan 12, 2016 at 20:57
67
votes
\$\begingroup\$

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

\$\endgroup\$
8
  • 35
    \$\begingroup\$ obligatory phpsadness \$\endgroup\$
    – wchargin
    Jun 1, 2014 at 4:12
  • 1
    \$\begingroup\$ I've got another PHP example: $a=2;echo "2+2=".$a++ + $a++; \$\endgroup\$
    – avall
    Jun 1, 2014 at 21:27
  • \$\begingroup\$ It's obvious that $a++ makes 3 and the result will be 6. I don't get what you're thinking. \$\endgroup\$
    – Ozh
    Jun 2, 2014 at 9:58
  • 1
    \$\begingroup\$ @Janus PHPsadness #30 explains it well \$\endgroup\$
    – wchargin
    Jun 3, 2014 at 4:13
  • 2
    \$\begingroup\$ Also trending on stackexchange... \$\endgroup\$ Jun 4, 2014 at 15:26
66
votes
\$\begingroup\$

JavaScript

var total = 2 + 2;

if(total = 5)
{
    alert('I guess 2 + 2 = 5');
}
else
{
    alert('The universe is sane, 2 + 2 = 4');
}
\$\endgroup\$
6
  • 73
    \$\begingroup\$ = instead of ==, easy to see and frankly rather uninspired. \$\endgroup\$ May 30, 2014 at 20:06
  • 19
    \$\begingroup\$ Have an upvote anyway, I make that mistake a lot \$\endgroup\$
    – user16402
    May 31, 2014 at 10:51
  • 6
    \$\begingroup\$ I still like this answer \$\endgroup\$ Jun 2, 2014 at 17:43
  • 5
    \$\begingroup\$ I like it too. Not every language uses = only as an assigment but a comparison operator (e.g. Pascal, SQL, VB) \$\endgroup\$
    – avall
    Jun 2, 2014 at 20:27
  • \$\begingroup\$ I find it very obvious \$\endgroup\$
    – Oliver Ni
    Jan 1, 2015 at 23:14
57
votes
\$\begingroup\$

C#

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

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

        Console.WriteLine(x + y);
    }
\$\endgroup\$
5
  • 7
    \$\begingroup\$ ah, the good old trick with rogue characters. That's why you should use 1TBS everywhere. \$\endgroup\$ May 30, 2014 at 17:52
  • 11
    \$\begingroup\$ @JanDvorak Does this work because of the semicolon after the if statement? I don't know C# but I have used C++ \$\endgroup\$
    – user16402
    May 30, 2014 at 18:31
  • 5
    \$\begingroup\$ @professorfish that's what I assume. Also, languages that don't let you insert random curly braces FTW. \$\endgroup\$ May 30, 2014 at 18:33
  • 12
    \$\begingroup\$ 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. \$\endgroup\$
    – Grax32
    May 30, 2014 at 18:58
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – mpen
    Jun 2, 2014 at 0:32
56
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – rgajrawala
    Apr 9, 2015 at 1:51
53
votes
\$\begingroup\$

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

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

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.

\$\endgroup\$
1
  • 16
    \$\begingroup\$ This is quite sly. Nobody ever looks at your imports/includes. \$\endgroup\$
    – user16402
    May 31, 2014 at 13:51
44
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 7
    \$\begingroup\$ Not bad, fooled me for a bit. \$\endgroup\$
    – qwr
    Jun 2, 2014 at 6:22
37
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • 7
    \$\begingroup\$ That's a very strange main signature. \$\endgroup\$ Jun 1, 2014 at 22:11
  • 10
    \$\begingroup\$ Java implements variadic arguments as arrays under the hood. \$\endgroup\$
    – CodaFi
    Jun 2, 2014 at 4:47
  • 4
    \$\begingroup\$ 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. \$\endgroup\$
    – Justin
    Jun 9, 2014 at 6:59
34
votes
\$\begingroup\$

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: [email protected]

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.

\$\endgroup\$
1
  • 11
    \$\begingroup\$ +1, This is very devious, because who the hell looks at the program that runs the source code when debugging? \$\endgroup\$
    – MrLore
    Jul 25, 2014 at 3:45
33
votes
\$\begingroup\$

JavaScript

Code:

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

Output:

5

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

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

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.

\$\endgroup\$
1
  • 16
    \$\begingroup\$ Nice use of unspecified behavior \$\endgroup\$
    – chbaker0
    Jun 5, 2014 at 0:34
24
votes
\$\begingroup\$

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.

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

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

\$\endgroup\$
2
  • \$\begingroup\$ Why ~eval(`a`) instead of just ~a? \$\endgroup\$ Jun 2, 2014 at 13:25
  • 2
    \$\begingroup\$ I wanted to leave some of the int() functionality and eval() does the job if the input is a stringified integer :) \$\endgroup\$
    – avall
    Jun 2, 2014 at 14:27
24
votes
\$\begingroup\$

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.

\$\endgroup\$
23
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Also: class Fixnum; def +(n) 5 end end; 2 + 2 # => 5 \$\endgroup\$
    – film42
    Jun 2, 2014 at 2:38
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Jun 5, 2014 at 3:26
20
votes
\$\begingroup\$

Scheme

(define 2+2 5)
2+2 ;=> 5
\$\endgroup\$
10
  • 9
    \$\begingroup\$ hey! 2+2 isn't how you do addition in lisp! \$\endgroup\$ May 30, 2014 at 17:54
  • 1
    \$\begingroup\$ So what? It seemingly add 2 to 2 as is in the task. \$\endgroup\$
    – Hauleth
    May 30, 2014 at 18:33
  • 119
    \$\begingroup\$ @JanDvorak I've never used lisp, but as I understand it it's something like ((((2))(()()))()()(()((((+))))()(((()(())((((2)))))()))(()))). \$\endgroup\$ May 31, 2014 at 4:00
  • 2
    \$\begingroup\$ "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 \$\endgroup\$
    – Felipe
    Jun 2, 2014 at 4:42
  • 1
    \$\begingroup\$ @FelipeMicaroniLalli that adnotation was made after my answer so it doesn't count. \$\endgroup\$
    – Hauleth
    Jun 4, 2014 at 8:36
19
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 6
    \$\begingroup\$ A range starting and ending at 2 would be just { 2 }, wouldn't it? \$\endgroup\$ May 31, 2014 at 22:12
  • 1
    \$\begingroup\$ @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). \$\endgroup\$ Jun 1, 2014 at 0:21
  • 14
    \$\begingroup\$ @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. \$\endgroup\$ Jun 1, 2014 at 0:29
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Paul
    Jun 2, 2014 at 13:38
19
votes
\$\begingroup\$

F#

Let's put in fsi following statement:

let ``2+2``= 5

Output:

val ( 2+2 ) : int = 5
\$\endgroup\$
18
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Nice; I can't upvote if undefined behavior isn't allowed. \$\endgroup\$
    – this
    Jun 1, 2014 at 13:27
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – ugoren
    Jun 1, 2014 at 14:18
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – this
    Jun 1, 2014 at 19:27
1
2 3 4 5 6

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