[Question]
  [
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
 
 
---
 This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
 
 
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.
  
[Answer]
## 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](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Integer.java#Integer.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](http://ideone.com/o1h0hR).
[Answer]
## 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](http://ideone.com/fork/16PScH)
> 
>  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.
> 
> 
> 
[Answer]
# 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
```
[Answer]
## 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  
> 
> 
> 
> 
[Answer]
## 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.
> 
> 
> 
[Answer]
# 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](https://i.stack.imgur.com/3XIm6.png)
> 
>  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.
[Answer]
## Brainfuck
```
+++++           +++++
    +               +    
    +     +         +     +++++
+++++    +++    +++++     
+         +     +         +++++
+               +
+++++           +++++.
```
Output:
```
5
```
Try it [here](http://esoteric.sange.fi/brainfuck/impl/interp/i.html).
I know this might sound a little to simple, but I tried to be creative, as suggested in original post.
[Answer]
# Bash
Since this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), 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`
> 
> 
> 
[Answer]
# 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.
[Answer]
# 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.
> 
> 
> 
[Answer]
# 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](https://www.noisemeters.com/apps/db-calculator.asp).
[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';`
> 
> 
> 
[Answer]
### JavaScript
```
var total = 2 + 2;
if(total = 5)
{
    alert('I guess 2 + 2 = 5');
}
else
{
    alert('The universe is sane, 2 + 2 = 4');
}
```
[Answer]
# C#
```
    static void Main(string[] args)
    {
        var x = 2;
        var y = 2;
        if (1 == 0) ;
        {
            ++x;
        }
        Console.WriteLine(x + y);
    }
```
[Answer]
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.
> 
> 
> 
[Answer]
# 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
> 
> 
> 
[Answer]
# 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](https://metacpan.org/pod/Acme%3a%3aNewMath). 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.
> 
> 
> 
[Answer]
## 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.
> 
> 
> 
[Answer]
# 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.
[Answer]
## 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]](/cdn-cgi/l/email-protection)
```
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. 
> 
> 
> 
[Answer]
**JavaScript**
Code:
```
var a = 3;
а = 2;
a + а;
```
Output:
```
5
```
You can test it yourself on your console or check this [Fiddle](http://jsfiddle.net/7j379/)
[Answer]
# 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.
> 
> 
> 
[Answer]
## 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`.
> 
> 
> 
[Answer]
## 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`
> 
> 
> 
[Answer]
## 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.
[Answer]
## 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](https://www.youtube.com/watch?v=vbX5BVCKiNs) and read [First-class environments](http://funcall.blogspot.com/2009/09/first-class-environments.html) from the Abstract Heresies blog.
[Answer]
# Scheme
```
(define 2+2 5)
2+2 ;=> 5
```
[Answer]
# 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.
[Answer]
# F#
Let's put in fsi following statement:
```
let ``2+2``= 5
```
Output:
```
val ( 2+2 ) : int = 5
```
[Answer]
## 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.
]