title: Write a program that makes 2 + 2 = 5

text:
# Question
Title: Write a program that makes 2 + 2 = 5
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
> 665 votes
## 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.

# Answer
> 294 votes
## 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.

# Answer
> 293 votes
# 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
> 183 votes
## 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.

# Answer
> 143 votes
## 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
> 135 votes
# 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.

# Answer
> 131 votes
## 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.

# Answer
> 105 votes
# 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`

# Answer
> 101 votes
# 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
> 86 votes
# 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
> 71 votes
# 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.

# Answer
> 67 votes
## 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
> 66 votes
### JavaScript

```
var total = 2 + 2;

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

```

# Answer
> 57 votes
# C#

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

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

        Console.WriteLine(x + y);
    }

```

# Answer
> 56 votes
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
> 53 votes
# 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
> 49 votes
# 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.

# Answer
> 44 votes
## 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
> 37 votes
# 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
> 34 votes
## Befunge

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

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

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

# email: MarkSmith@example.com

```

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

Explanation:

> A Befunge program is made up of a grid of single character commands. The first command is the one in the top left corner, and the reading of commands proceeds to the right. But the direction can change during program execution.
> Only the first row of characters, and the column of characters starting with the `v` in the first row are run. The characters in question do:
> `#` \- skip the next command
> `>` \- From now on, commands are read to the right of the current command
> `v` \- From now on, commands are read below the current command
> `5` \- Push 5 to the stack
> `.` \- Pop and print the number at the top of the stack
> `@` \- End the program
> `<space>` \- Do nothing
> If you knew you were programming in Befunge, this wouldn't really trick anyone. But if you came across this and didn't realize it was Befunge, it most likely would.

# Answer
> 33 votes
**JavaScript**

Code:

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

```

Output:

```
5

```

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

# Answer
> 29 votes
# 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
> 24 votes
## 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
> 24 votes
## 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
> 24 votes
## 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
> 23 votes
## 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.

# Answer
> 20 votes
# Scheme

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

```

# Answer
> 19 votes
# F#

Let's put in fsi following statement:

```
let ``2+2``= 5

```

Output:

```
val ( 2+2 ) : int = 5

```

# Answer
> 19 votes
# 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
> 18 votes
## 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.

# Answer
> 16 votes
# Javascript

Here is another fun one. This time in Javascript

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

alert(Add(2,2));

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

```

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

# Answer
> 14 votes
# 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.

# Answer
> 11 votes
# C

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

### First Solution

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

```

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

### Second Solution

```
#include <errno.h>

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

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

    free( buffer );
    return 0;
}

```

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

# Answer
> 10 votes
## Python

Computers really use binary to add.

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

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

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

```

Try it.

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

# Answer
> 10 votes
# piet

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

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

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

# Answer
> 9 votes
## 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!

# Answer
> 9 votes
# C

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

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

```

Logs: 5

---

This one was a lot of fun!

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

# Answer
> 8 votes
## Commodore 64 Basic

```
1 POKE 2070, 51
2 PRINT 2+2

```

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

# Answer
> 7 votes
# Windows Command Script

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

```

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

# Answer
> 7 votes
# Python

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

```

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

# Answer
> 6 votes
# Perl 6

I have no idea why it happens. Help.

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

```

# Answer
> 6 votes
# Javascript: (8 bytes)

```
2+2|!![]

```

# Explanation:

(*requested in comments*)

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

Another example:

```
2+2|!""

```

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

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

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

```

or plain which is **shortest (5 bytes)**

```
2+2|1

```

but putting 1 in there makes is too obvious.

# Answer
> 6 votes
# FORTH

```
: 2 ; : + 5 ; 2 2 +

```

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

# Answer
> 6 votes
# Javascript

Use an array.

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

```

Will output

```
5

```

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

# Answer
> 6 votes
# Mathematica

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

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

```

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

```
In[2]:= 2*3

Out[2]= 6

```

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

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

Out[3]= True

```

And it certainly does not equal 5:

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

Out[4]= False

```

So now, let's evaluate 2+2:

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

Out[5]= 5

```

Oops!

> $Post is a function that is applied to every expression after normal evaluation. `...&` defined an anonymopus function, and `#` refers to the argument. `SquareFreeQ` gives true if the expression does not contain a factor that is a square (other than 1), `!` is the logical not, as usual, anmd `Boole` converts the logical value into `0` for `False` and `1` for `True`.
> Since `6` is square free, the first test is not affected by this: Adding `0` to `6` doesn't change anything.
> One might expect an error on the tests giving `True` or `False`, but `SquareFreeQ` just gives `True` on such values (the same is true for the non-printed `Null` generated by the first line; otherwise it would have generated `Null+1` which would have been printed). Also, the obviously meaningless addition `True+0` is no problem for Mathematica; you can add 0 to *anything* (even a picture, if you desire) and it won't change anything. Therefore also those tests give the expected result.
> Finally, we arrive at `2+2`. This results in `4`, which is not square free, thus `$Post[4]` evaluates to `5`, which is what gets output.

# Answer
> 5 votes
# Ruby

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

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

p sum(2,2)

```

# Answer
> 5 votes
# Rebmu

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

```
stLDtsTC43a&[5]

print do [2 + 2]

```

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

The transparent version of the poisoning line would be:

```
+: function [dummy-parameter] [5]

```

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

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

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

---

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

```
>> protect '+

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

```

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

# Answer
> 5 votes
# T-SQL

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

select "2 + 2"

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

```

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

# Answer
> 5 votes
**Perl**

```
use strict;

sub calculator ($) { @_ }

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

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

# Operation
push @calculation, "+";

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

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

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

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

# And a blank line
print "\n";

```

# Answer
> 5 votes
## JavaScript

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

```

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

# Answer
> 5 votes
# Haskell (Proof by Curry-Howard Isomorphism)

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

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

import GHC.TypeLits

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

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

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

infix 4 ==

```

# Answer
> 5 votes
# DUP

```
It's simple: 2+2=5.

```

`Try it here.`

Hehe, good luck with this one.

# Explanation

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

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

# Answer
> 4 votes
# Ruby

```
class Fixnum
  def +(num)
    5
  end
end

2 + 2
# => 5

```

# Answer
> 4 votes
# HTML + CSS

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

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

```

http://jsfiddle.net/4rNLM/

# Answer
> 4 votes
# C#

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

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

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

        Console.WriteLine(num1 + num2);
    }
}

```

# Answer
> 4 votes
# JavaScript

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

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

```

**Demo Here**

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

# Answer
> 4 votes
# PHP

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

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

```

That simple script will output `5`.

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

# Answer
> 4 votes
# PowerShell

And swing

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

sum 2+2  #5

```

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

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

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

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

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

```
function 2+2 {
    5
}

```

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

# Answer
> 4 votes
# COBOL

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

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

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

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

```

Result:

> 1 + 2 + 1 = +0000000005

.

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

# Answer
> 4 votes
## APL

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

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

```

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

# Answer
> 3 votes
# C#

```
using System;

namespace AdditionFoo
{
    class Number
    {
        private int m_value;

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

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

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

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

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

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

            var c = a + b;

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

```

# Answer
> 3 votes
# C++

```
#include <iostream>
using std::cout;

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

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

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

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

    delete[] two;
    return 0;
}

```

# Answer
> 3 votes
# Python 3

<sub><sub>\>\>\> ₓ2 = 3</sub></sub>

<sub><sub>\>\>\> print("2+2 =",ₓ2+2)</sub></sub>

<sub><sub>2+2 = 5</sub></sub>

<sub><sub>Don't downvote; try it by cut and pasting.</sub></sub>

<sub><sub>Hint:</sub></sub>

> <sub><sub>To find out, hold Ctrl+= (Zoom) and look carefully:</sub></sub>

<sub><sub>Additional Hint:</sub></sub>

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

# Answer
> 3 votes
# Coq

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

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

```

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

# Answer
> 3 votes
**C/C++**

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

```

hidden.h:

> #define ＋ + 1 +

The answer (if it's not obvious)

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

# Answer
> 3 votes
# Java

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

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

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

```

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

# Answer
> 3 votes
## Emacs Lisp

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

(+ 2 2) ;; => 5

```

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

# Answer
> 3 votes
# C#

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

```

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

# Answer
> 3 votes
## Batch

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

```

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

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

# Answer
> 3 votes
**C**

Two fun entries,

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

    return 0;
}

```

and

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

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

    return 0;
}

```

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

The magic:

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

# Answer
> 3 votes
## Scratch

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

```

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

# Answer
> 3 votes
# Ruby

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

```

Some Ruby `pack` magic!

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

# Answer
> 3 votes
## R

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

```

# Answer
> 3 votes
# \>\<\>

Nowhere near the best, but it was fun to make

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

```

## Output

```
5

```

## Explanation

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

# Answer
> 3 votes
# TI-BASIC:

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

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

```

Let's try it...

```
prgmFOUR
               5

```

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

# Answer
> 3 votes
# C89

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

```

A little explanation:

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

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

```

# Answer
> 3 votes
# MATLAB

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

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

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

```

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

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

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

```

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

```
plus(3,3)
ans =
     6

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

```

And of course:

```
plus(2,2)
ans =
     5

```

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

# Answer
> 3 votes
## MATLAB

I think this one can be quite deceiving as well.

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

```

Printing

```
2+2 =     5

```

Or alternatively

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

```

Printing

```
2+2=5

```

# Answer
> 3 votes
# Octave

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

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

```

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

# Answer
> 2 votes
# Javascript

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

```

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

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

# Answer
> 2 votes
# JavaScript

This isn't really particularly inspired, but:

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

```

or perhaps

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

```

# Answer
> 2 votes
## Python 3

A rather trivial example from me.

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

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

```

To test, combine with this:

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

```

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

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

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

# Answer
> 2 votes
## C

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

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

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

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

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

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

}

```

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

# Answer
> 2 votes
# Javascript

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

```

JSFIDDLE

# Answer
> 2 votes
# PHP (\<5.3.11)

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

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

```

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

# Answer
> 2 votes
# CoffeeScript

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

```

Try it here

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

Actually try to figure it out before looking at the spoiler

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

Still don't get it?

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

# Answer
> 2 votes
# MySQL

Here my simple SQL solution to the problem:

Database structure:

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

```

Query:

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

```

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

# Answer
> 2 votes
# GolfScript

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

2 2+

```

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

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

2 2+

```

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

```
{;5print}:puts

2 2+

```

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

# Answer
> 2 votes
# Javascript (should work in a bunch of other languages too):

It adds what looks like 2+1+1

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

Try doing the math yourself:

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

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

# Answer
> 2 votes
## Perl 5

**Example 1**

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

```

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

**Example 2**

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

```

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

**Example 3**

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

```

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

# Answer
> 2 votes
# TI 30 Calculator

```
2nd ÷ +1

```

## Examples

`3+4` = 8

`9*5` = 46

`sqrt(16)` = 5

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

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

# Answer
> 2 votes
# Mathematica

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

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

> 2 + 2 // Hold // ReleaseHold
5

```

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

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

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

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

```

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

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

# Answer
> 2 votes
# C++

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

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

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

```

This prints to the console:

```
2 + 2 = 5

```

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

# Answer
> 2 votes
# MATLAB

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

```

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

:)

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

# Answer
> 2 votes
# Whitespace, (looks like C++)

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

raw paste data here.

online interpreter here.

```
#include<iostream>

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

    return  0;

}

```

If you run it in C++ it prints

```
4

```

If you run in whitespace it prints

```
2+2=5

```

# Answer
> 2 votes
# AppleScript

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

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

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

Output:

```
5
```

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

# Answer
> 2 votes
**C**

```
#include "stdio.h"

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

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

```

It outputs:

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

```

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

**NOTE**

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

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

```

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

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

```

# Answer
> 2 votes
# Python 3

An extremely lame one, inspired by this MATLAB answer.

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

```

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

Proof it Works On My Machine™

Here's *more* proof it works.

Also:

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

```

# Answer
> 2 votes
# C++

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

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

```

Output: 2 + 2.0 = 5

# Answer
> 1 votes
# GolfScript

```
2,~2,~],

```

What the program does:

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

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

Explanation:

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

# Answer
> 1 votes
## Java

Using reflection:

```
import java.lang.reflect.Field;

public class TwoPlusTwoTest {

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

```

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

## JavaScript

Using an overloaded `valueOf`:

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

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

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

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

```

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

# Answer
> 1 votes
# JavaScript

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

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

(2+2).toString()

```

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

# Answer
> 1 votes
## Factor

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

IN: scratchpad 2 2 + .
5

```

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

# Answer
> 1 votes
## Befunge93

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

```

Try it online.

**Explanation**

> The `=` functions as a mirror for the instruction pointer (in Befunge93), so the phrase itself is not "executed". The pointer goes this way:
> `2` \- put 2 on the stack
> `+` \- add 2 to 0 (i.e. do essentially nothing)
> `2` \- put another 2
> `=` \- instruction not defined: inverse the direction of the pointer
> `2` \- put another 2
> `+` \- add 2 to 2 - put 4
> `2` \- put 2. Wrap to the end of the line
> `!` \- logical negation for 2: put 0
> `!` \- logical negation for 0: put 1
> `+` \- add 1 to 4 - put 5
> `.` \- print 5
> `@` \- exit

# Answer
> 1 votes
## Javascript

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

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

```

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

# Answer
> 1 votes
# Befunge 98

```
"2+2".@

```

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

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

# Answer
> 1 votes
# Python

It's legit, I swear!

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

```

# Answer
> 1 votes
**Ocaml**

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

```

# Answer
> 1 votes
# Apple Swift

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

```

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

# Answer
> 1 votes
# JavaScript

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

```

Output: 5

# Answer
> 1 votes
# T-SQL

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

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

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

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

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

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

```

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

# Answer
> 1 votes
# Java

How about this,

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

```

output: 5

# Answer
> 1 votes
# \>\<\>

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

```

Outputs "5". How it works:

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

# Answer
> 1 votes
# C++

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

### METHOD 1

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

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

```

### METHOD 2

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

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

```

## METHOD 3

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

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

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

```

# Answer
> 1 votes
# C++

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

```

Output:

```
2+2=5

```

How it works:

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

# Answer
> 1 votes
# C

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

```
#include <stdio.h>

#define a a=5,b

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

```

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

# Answer
> 1 votes
# Hassium

Not the most creative but here goes:

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

```

Run code online

# Answer
> 1 votes
# Python 2

Here's another python one.

```
import sys

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

print 2 + 2

```

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

# Answer
> 1 votes
# Swift

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

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

print(2+2)

```

# Answer
> 1 votes
## Python 2 (and maybe 3?)

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

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

```

Run this and it outputs:

```
2+2=5

```

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

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

# Answer
> 1 votes
# Mouse-2002

Mouse is a language about mathematical equation solving.

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

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

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

```
a 2 + 2 = 5 !
> 5

```

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

# Answer
> 1 votes
# Python 3

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

```

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

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

```

Or just obfuscate it completely:

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

```

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

---

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

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

---

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

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

---

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

* `76 / 19`
* `pow(3, 4)`
* `1 / 4`

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

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

```

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

```
>>> print(1 / 4)
4.0
0.2

```

# Answer
> 1 votes
# Retina

```
<empty>
2+2=?
.

```

`Try it online!`

# Explanation

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

# Answer
> 1 votes
# CJam

```
X(2+2)+0;

```

Doesn't look like CJam? Think again.

# Explanation

```
X(        e# push (X=1) decremented to stack [0]
  2       e# push 2 to stack                 [0 2]
   +      e# add                             [2]
    2)    e# push 2 incremented to stack     [2 3]
      +   e# add                             [5]
       0  e# push 0                          [5 0]
        ; e# pop and discard                 [5]
          e# implicit stack output

```

# Answer
> 1 votes
## PowerShell

```
$c=2                                                   # Set variable = 2
Write-Host ("$c + $c = " + $(2+($c++,$c--)[$c-eq2]))   # Perform the addition and output
Write-Host ("c = $c")                                  # Show that $c is still = 2

```

**Output:**

```
PS C:\Tools\Scripts\golfing> .\2-plus-2.ps1
2 + 2 = 5
c = 2

```

**What the deuce?**

Hint 1:

> First, understand that the code `(a, b)[c]` (replacing a,b,c for values/variables) is a pseudo-ternary in PowerShell, where the dynamic array `(a, b)` is indexed into based on the value `c`.

Hint 2:

> Next, understand that `$true = 1` and `$false = 0` and that arrays are zero-indexed. Thus, depending upon whether `$c-eq2` ("$c is equal to 2") is `True` or `False`, we'll choose either the second or first value, respectively, and add that on to the `2`.

Hint 3:

> The dynamic array gets calculated before indexing.

Explanation:

> The increment and decrement *don't* get evaluated twice. Instead, they're evaluated before the rest of the expression. Since we're creating a dynamic array, the first element of the array is processed as `$c` and saved as `2`, and *then* the post-increment happens and sets `$c=$c+1=3`. The second element is processed as `$c` and saved as `3` (since `$c` was just set to `3`), and *then* post-decremented back to `2`. This makes our array `(2,3)`. We index into that with `$c-eq2` ... well, `$c` is now `2` again, so that evaluates to `$true`, or `1`, and so selects the second element of the array, `3`. Thus `2+3=5`. And, since `$c` was decremented back down, we get the bonus of being able to output `c = 2` still.

# Answer
> 0 votes
**F#**

```
let plus a b =
    match (a, b) with
    | (2, 2) -> 5
    | _ -> a + b

```

# Answer
> 0 votes
## C

Is this too obvious?

```
#include <stdio.h>
int main()
{
int a=2,b=2,i=0;
int n=a+b;
for(;i<=n;++i){}
printf("%d\n",i);
getchar();
return 0;
}

```

## JavaScript

```
alert("2 + 2".length);

```

# Answer
> 0 votes
# Scheme (R7RS/R6RS)

```
#!r7rs            ; or #!r6rs
(import (scheme)) ; or (import (rnrs))

(define (dec x)
  (- x l))

(define (inc x)
  (+ x 1))

(define (peano+ a b)
  (if (>= a 1)
      (peano+ (dec a) (inc b))
      b))

(define l 1/2)
(define i 3/2)
(define f 5/2)
(define e 87/32)

(display (peano+ 2 2))
(newline)

```

How it works:

> In the dec procedure i reduce by lower case L, which is a free variable. I define it lower down to be 1/2.(an exact number in Scheme) So my peano arithemtic procedure adds 1 to b but reduces a by 1/2 and since my base case does not stop at zero but everything below 1 (peano+ 2 2) ends up being 5.

# Answer
> 0 votes
# Clojure

```
(let [+a clojure.core/+]
  (intern 'clojure.core '+ (fn [& args] (if (= [2 2] args) 5 (apply +a args)))))

```

# Answer
> 0 votes
Java using unicode - this trick will probably work exactly the same in many other languages

For simplicity I will post 2 programs: The first one generates the second. The second one does the evil 2+2=5 but will be hard to read without the first one for context.

The generator:

import java . io . * ;

```
class main
{
    public static void main ( String [ ] args ) throws Exception
    {
    Writer writer = new FileWriter ( "stuff.java" ) ;
    writer . append ( "class stuff\n{\n\tpublic static void main ( String [ ] args )\n\t{\n\t\tint a\u00082=2; \n\t\tint b\u00082=3;\n\t\tSystem.out.println( a\u00082 + b\u00082  );\n\t}\n}" ) ;
    writer . close ( ) ;
    }
}

```

The evil program. It appears as below on my console.

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

```

It outputs "5".

The trick:

I used control character for backspace \u0008 in the variable names. So my variable names are really "a backspace 2" and "b backspace 2" which are printed out on my console "2" and "2" respectively. When I examine the source code in my editor, they appear as "a^H2" and "b^H2".

# Answer
> 0 votes
# Python 2

Yeah, not very original, but hey.

```
class int(int):__add__=lambda *a:5
print int(raw_input("Number? ")) + int(raw_input("Number? "))

```

`int` is still perfectly normal, except all additions return 5. Doesn't affect literals.

# Answer
> 0 votes
template metaprogramming

```
#include <iostream>
#include <utility>
#include <type_traits>

enum class values {
  zero = 7,
  one = 3,
  two = 1,
  three = -7,
  four = 2,
  five = 4,
};

template<class T, T... ts> struct list {typedef list type;};
template<unsigned max, unsigned... ts> struct make_indexes:make_indexes<max-1, max-1, ts...>{};
template<unsigned... ts> struct make_indexes<0, ts...>:list<unsigned, ts...> {};
template<unsigned max> using make_indexes_t=typename make_indexes<max>::type;

template<class list> struct length_of;
template<class T, T... ts> struct length_of<list<T, ts...>>:std::integral_constant<unsigned, sizeof...(ts)> {};

template<class T, T t, class list> struct index_of;
template<class T, T t, T t0, T...ts> struct index_of<T, t, list<T, t0, ts...>>:
  std::integral_constant< unsigned, index_of<T, t, list<T, ts...>>::value+1 >
{};
template<class T, T t, T...ts> struct index_of<T, t, list<T, t, ts...>>:
  std::integral_constant< unsigned, 1 >
{};
template<class T, unsigned N, class list> struct value_at;
template<class T, unsigned N, T t0, T... ts> struct value_at<T, N, list<T, t0, ts...>>:value_at<T, N-1, list<T, ts...>> {};
template<class T, T t0, T... ts> struct value_at<T, 0, list<T, t0, ts...>>:std::integral_constant<T, t0> {};

template<class T> struct summable {};
template<> struct summable<values> {
  typedef values T;
  typedef list<T, T::zero, T::one, T::two, T::three, T::four, T::five> list_type;
  template<T t>
  using index = index_of< T, t, list_type >;
  template<unsigned N>
  using value = value_at< T, N, list_type >;
};

template<class T, template<T>class indexer>
unsigned index( T t, list<T> ) {
  return -1;
}

template<class T, template<T>class indexer, T t0, T... ts>
unsigned index( T t, list<T, t0, ts...> ) {
  if (t==t0)
    return indexer<t0>::value;
  else
    return index<T, indexer>( t, list<T, ts...>{} );
}

template<class T, template<unsigned>class valuer>
T value( unsigned N, list<unsigned> ) {
  return static_cast<T>(-1);
}
template<class T, template<unsigned>class valuer, unsigned M0, unsigned... Ms>
T value( unsigned N, list<unsigned, M0, Ms...> ) {
  if (N-1==M0)
    return valuer<M0>::value;
  else
    return value<T, valuer>( N, list<unsigned, Ms...>{} );
}

template<typename T>
T sum( T lhs, T rhs ) {
  typedef typename summable<T>::list_type list_type;
  return value<T, summable<T>::template value>( index<T, summable<T>::template index>(lhs, list_type{})+index<values, summable<T>::template index>(rhs, list_type{}), make_indexes_t<length_of<list_type>::value>{} );
}

template<typename T, typename=typename summable<T>::list_type >
T operator+( T lhs, T rhs ) {
  return sum( lhs, rhs );
}

```

all of which leads to this `main`:

```
int main() {
  auto two = values::two;
  auto five = values::five;
  std::cout << (two+two==five) << "\n";
  return 0;
}

```

which prints `1`.

> Mainly a game of misdirection. The `enum` values are not used anywhere in the code (so long as they are distinct). The `template` metaprogramming builds an entire infrastructure allowing positional-based addition of a list of values (regardless of their literal values) at compile time, and then a magic-switch construct converts this compile-time support to run-time support with sensible error messages. The indexes of elements are 1-based (so the first element is `1`), and the reverse map does this properly. The only part where it fails is when we add together two elements: we add together their 1-based index. As `two` is in the 3rd position, we get the 6th position result, which is `five`.

# Answer
> 0 votes
## C++11

Kinda cheap, but whatever...

```
#include <iostream>

class mynumber
{
public:
    unsigned long long n;
    unsigned long long operator+(mynumber rhs)
    {
        return n + rhs.n + 1;
    }
};

constexpr mynumber operator"" _ (unsigned long long n)
{
    return mynumber{n};
}

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

```

# Answer
> 0 votes
# C

Tested on OS X Mavericks with /usr/bin/gcc (i.e. clang). Results will likely vary on different machines, compilers, libraries, etc...

```
main() {
    char buf[80];

    char fmt[] = "2 + 2 = \
    /* long long n requires 'll' prefix *\
    %lln";

    /* use a long long to avoid overflow in computing 2+2 */
    /* (that's typically how we get the wrong answer.) */
    long long n = 2;

    /* print out n + n, that is: 2 + 2 */
    sprintf(buf, fmt, &n + n);

    puts(buf);
}

```

**Update:** added Linux version:

```
#include <stdio.h>
main() {
    long long n = 2;
    char buf[80];
    sprintf(buf, "2 + 2 =\
        /* 'll' prefix for long long *\
        %lln\n", &n + n);
    puts(buf);
}

```

Output:

```
$ ./five
2 + 2 = 5

```

Explanation:

> The `printf` format `%n` is not a format specifier, it instead instructs printf to store the number of characters written so far in the `int *` argument parameter. The `ll` prefix tells printf that the argument is a `long long` pointer, thus 64-bits. The first comment "inline" in the string, is not actually a comment, but part of the format string, giving the entire format string enough padding that the `%lln` occurs at the 53 index---the ASCII code for '5'. The `sprintf` argument of '&n + n' points 8 characters into the format string. So `sprintf` writes the 64-bit value 53 to that offset in the buffer. On a little-endian intel that corresponds to the bytes `{53, 0, 0, 0, 0, 0, 0, 0}`, thus nicely zero-terminating our string so the "inline" comment is not also output with the `puts`. I ran out of ideas for obfuscating it further, the line continuation comment seemed a little better than alternatives I tried, but if anyone has suggestions, they're very welcome!

# Answer
> 0 votes
## C/C++ cmath

The curse of the numbers below 473 and above 474...

```
#include <iostream>
#include <cmath>
#include <stdlib.h>

const int MaxA=5;
const int MaxB=5;
int A[] = {469,  470 , 471 ,472, 473};
int B[] = {474,  475 , 476 ,477, 478};

int Check_And_Calculate(int d, int c1,int c2){
 // It does a check on c1 and c2 and return the value of `-cubic root of c1^3` //
 if (c1>c2) std::cerr << "# "<< c1 << " is **BIGGER** then " << c2 << std::endl;
     else   std::cerr << "# "<< c1 << " is NOT bigger then " << c2 << std::endl;
 return  -cbrt(c1*c1*c1)   ;
}

int main()
{
  int a=2, b=2;
  srand48(time(NULL));               // Random seed: Randomize the seed...
  int ValueA=A[int(MaxA*drand48())]; // It Extracts one random element from A
  int ValueB=B[int(MaxB*drand48())]; // It Extracts one random element from B

  a=a+Check_And_Calculate(a,ValueA,ValueB)+ValueB;  // It adds B subtracts A
  b=b+Check_And_Calculate(b,ValueB,ValueA)+ValueA;  // It adds A subtracts B

  std::cout << "2+2=" << a+b << "\n";
  return 0 ;
}

```

Output

```
# 473 is NOT bigger then 476
# 476 is **BIGGER** then 473
2+2=5

```

Explanation

> We could say that the **A** group are the good ones (at least this time) and the **B** ones are the **Bad Guys**. (They have a lot of friend! see below).
> For some numbers we can observe the following behaviour for the *cubic square root function*, **cbrt(x)** and for the *power one* **pow(x,1./3.)**
> 3^3=27
> *pow(27.,1./3/)*= 3.0000000000000004
> 15^3=3375
> *pow(3375.,1./3/)*=14.999999999999998
> When it is returned by an integer function it is made an automatic *cast*:
> 3.0000000000000004 becomes 3
> 14.999999999999998 becomes 14
> So at the end it seems it was not a *curse* but only a problem of *bad casting*...

Notes:

> The comparison in the function is needed (or some other code at least) else when it is compiled with `-O1`,`-O2`,`-O3` option the code is substituted and the effect disappears.
> **The Wild Bunch**
> int MaxB=147;
> **B**\[\]={15,27,30,37,54,60,67,71,74,108,117,119,120,134,139,142,148,161,191,205,216,221,225,229,234,237,238,239,240,253,268,278,284,296,315,322,382,407,410,417,431,432,439,441,442,443,445,449,450,458,465,468,474,475,476,477,478,480,481,487,501,505,506,527,536,551,556,563,567,568,592,593,630,641,644,743,751,764,775,791,801,814,820,829,834,857,861,862,864,867,878,879,882,884,886,890,898,900,903,905,907,915,916,923,925,927,929,930,936,947,948,950,952,954,955,956,957,960,962,967,971,974,975,983,1002,1010,1012,1017,1021,1027,1031,1054,1072,1102,1112,1126,1133,1134,1136,1181,1184,1186,1213,1249,1260,1279,1282}

# Answer
> 0 votes
**A C++ template metaprogram:**

```
#include <iostream>
#include <conio.h>

using namespace std;

template <int a, int b>
int add()
{
    return a + b;
}
template<>
int add<2, 2>()
{
    return 5;
}

int main()
{
    cout << "2 + 3 = " << add<2, 3>() << endl;
    cout << "2 + 2 = " << add<2, 2>();
    _getch();
}

```

The output will be:

```
2 + 3 = 5
2 + 2 = 5

```

# Answer
> 0 votes
# GolfScript

```
5:4;'"#{'"#{STDIN.gets}"-1<'}"'++~~

```

The program gets a line from STDIN, then evaluates it. Example run:

Input:

```
2 + 2

```

Output:

```
5

```

How it works:

> The `5:4;` assigns the value of `5` to 4. But simply computing `2 2+` would result in `4`. So the rest of the program reads a line from STDIN, removes the trailing newline, then evaluates `"#{line from stdin}"` to let ruby add the numbers. So an input of `2 + 2` leaves a `"4"` on the stack. Lastly, we evaluate it again, resulting in `5`.

# Answer
> 0 votes
# JavaScript

```
var two = {
    valueOf:function() { return 2; }, //two = 2
    toString:function() { return '3-1=2' } //interesting fact
}
var stringToPrint = '';
stringToPrint += "2 + 2 = " + two + two;
alert(stringToPrint);
alert("Oops, string concatenation instead of addition");
stringToPrint = '';
stringToPrint += "2 + 2 = " + (parseInt(two) + two); //convert a two to integer first
alert(stringToPrint); // 2 + 2 = 5 finally!

```

# Answer
> 0 votes
**Mathcad**

```
x:2
y:2
Given
x+y-4⎈=⎈!⎈!c
Find(x+y)=

```

Gives `5`.

means the `Ctrl` key. It may not display properly in some browsers.

> The trick is in the `Given` part. `Given` and everything that comes after it and before `Find` is called the `Solve Block`. The function `Find` will give the values of the variables which you pass to it which satisfy the equations inside the `Solve Block`, looping through the possible values of variables starting from their original values, in this case, `x=2` and `y=2`. Here, the equation inside the `Solve Block` is `x+y-4⎈=⎈!⎈!c`, which gets formatted as `x+y-4=¬¬c`. Mathcad doesn't distinguish between scalars and booleans, just like ol' C89. And `c` is a built-in variable that stores an approximation of the speed of light in vacuum. So `¬¬c` gives `1`. This makes the equation `x+y-4=1`, and the only value of `x+y` that satisfies it is `5`.

# Answer
> 0 votes
**C (gcc-4.9.2, gcc-4.8.3 and probably other gcc compilers)**

A different variant of a previously posted answer.

```
#include <stdio.h>

int main(void) {
    int i = 1;
    printf("%d\n",
                ++i //++i returns 2, i is now 2
                + i++ //i++ returns i, i.e. 2
    );
    return 0;
}

```

(see it online here)

> Same trick as https://codegolf.stackexchange.com/a/30138/36458, GCC actually evaluates them the other way around.

# Answer
> 0 votes
### C#

I believe it works for .net framework \<= 4.0

```
static void Main(string[] args)
    {
        Func<int, int> tmp = null;
        for (int i = 2; i < 3; i++)
            tmp = (x) => { return i + x; };
        Console.WriteLine(tmp(2));
    }

```

# Answer
> 0 votes
**PowerShell**

```
#Make a character array string with the equation in it
#Measure the value, explicitly as a calculation
#Show only the resulting 'amount'
#(Golfed with short aliases and wildcard 'amount' for extra oomph)

[char[]]'2 + 2'|Measure -Sum|Select -Exp *t
5

```

> Nope, it measures the length of the string: 5 chars. It casts the string as char array, pipes those to Measure-Object; An array going into the pipeline is split into the contents, so there are five things to count. Measure-Object results in an object with these properties: `{Count:5,Average: ,Sum:207, ...}`. Then `Select -Exp *t` is a wildcard, but it matches the Count property instead of the non-existent 'Amount'; takes the value, and drops the rest. (`-Sum` is a thing, here adding up the ASCII character values, but I'm using it as a diversion)

# Answer
> 0 votes
# Lua:

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

a = 2
b = 2

print(a + b) -- 5

```

Try it

# Answer
> 0 votes
# Python 2

yay operator overloading :P

```
class int:
    number = 2
    def __init__(self, number):
        self.number = number
    def __add__(self, other):
        return self.number + other.number + 1

two = int(2)   # works without above def!
print two + two

```

try on ideone!

> pretty simple to understand, just overwrites the int class with a new one that adds one to each addition thing. Seriously I'm surprised `print 2+2` by itself doesn't work.

# Answer
> 0 votes
# Vitsy

```
22+3mN
Since Vitsy is a stack language, it pushes 2 to the stack,
then another 2, then adds them. Even so, it will do the following equation:
2+2=5
```

Output:

```
5
```

> Visty may be stack based and 1D, but it can execute specific lines of a file (3m goes to the third line) What really happens here is 2+2, then push another 2 to the stack. Add the top two items, making the only item 6, pushes another 2, checks if the top two items are equal. If it's not (which it isn't), it pushes zero. Then, push 5 to the stack, and, finally, output the top item of the stack as a number.

# Answer
> 0 votes
# PHP

```
var_dump(2 + 2 === (int)((0.1 + 0.7)*18.75/3) ? true : false);

```

Ok, before you say "wtf? Where is the 2+2=5 here?", bear with me:

```
0.1 + 0.7 = 0.8
0.8 * 18.75 = 15
15/3 = 5

```

And we all know that `5 = 5.` So there is nothing wrong changing that, right? It should print false, right? Well... that's not the case. And here is the reason.

# Answer
> 0 votes
# F#

```
let(+)_ _=5
2 + 2

```

There are other F# answers here, but I'm not sure why no one posted this one.

> It simply redefines the result of addition operators to be the number `5`.

Too obvious? A somewhat sneaker alternatively you would be:

```
let(~+)_=3
+ 2 + 2

```

> It redefines the result prefix `+` to operator to be the number `3`. The second `+` is normal addition. Note the space between the first `+` and the `2` is required to make the parser read it as an operator and not a literal; the other spaces are not required.

But this isn't underhanded enough. What about:

```
let printfn t 4=printfn t 5
printfn "2 + 2 = %i" (2 + 2)

```

> This doesn't change the actual result value of `2 + 2`, it just changes what happens to get printed to the screen in output messages.

# Answer
> 0 votes
# TeaScript

```
\2+2=5\;
2+2

```

Outputs: `5`

---

This also works:

```
\2+2=5\

```

---

Whaaat?

---

> `2+2=5`? Sure, the TeaScript compiler just rolls with it
> This feature is supposed to be used for golfing so you could do `\p=n++\;p` and that would compile to `n++;n++`. Essentially compile-time variables

# Answer
> 0 votes
# ngn/apl

```
+←=++

```

> Reassigns X+Y to be a fork, viz. the sum of X=Y (which is 1 in the case of 2+2) and X+Y.

```
      +←=++
      2+2
5

```

Try it here.

# Answer
> 0 votes
# Bash

```
alias +="printf'5\n'" 2+2=+ 2+=+ +2=+ 2=

```

After pasting/typing that in to your console, typing `2+2`, `2 + 2`, `2+ 2`, and `2 +2` will all print `5` and a newline.

For more golfiness, `alias 2+2="printf'5\n'"` also works.

# Answer
> -1 votes
## PHP

Here are 2 methods I found working

**Method 1**

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

```

**Method 2**

```
$a = $b = 2;
echo ($a + ++$b);

```

# Answer
> -1 votes
**Python 2.7 a emotional answer to the problem**

```
# Code and error numbers for all errors that can occur.
error_number = 53
error_descrption = "Error occured"

try:
    bird;
    """

    This is the lead motive of our application.
    This was made by jrei (http://www.chris.com/ascii/index.php?art=animals/birds%20(land))

                               _,---._      __,...-----...___
                           _,-:::,,--.`,--''                 `'--._
                         ,':::::/((##)):                           `-.
                       ,':.::::/  `--' :         _____.....______ (:::\
                      /:::::::/        :__,.-''''..- - - - --  -- .`_-:\
                     /:,:::.::|        ::.          ____....-----.....`.
                    /,:::::::/          ::::__.--'''
                    |:::::::|           _:'
                    |:.:::::|         ,'
                    |:::::::|         |
                   /::::.:::|         |
              __,-'::.::::::|         |
       _,.--''::::_::::::::::\        |
     ''::_::,:--''  `'--.:::::\       ;
     -'''::::::::::::::::\:::::`.     ;
     :::::::::::::::::::::|:.::::`-..-
     ::;::::::::::::::::::|::::::::::/
     :/::::::/::::::;:::::|::::.::::/
     (::::::/::::::/::::::):.::::::'
     :`:__,;::::::;:::::,':::::::'
     ,-':::`.__,-'::::,'::::::-'
     :::::,-'::::::,-':::_:-'
     _,-':::::::,-'::_:-'
     jrei::::,-_:--''
      ::,::--''

    I think it resembles our application the best.
    The strength and the speed of the bird are the same characteristics as our
    application.

    So dear reader enough talk, now comes the code which makes the application so
    incredible! Buckle up your seatbelts! It will be a tough ride.

    """

    print "{}".format(2+2)

    """
    Oh dear reader i forgot to show you, how this program actually is structured.
    I think the best way is UML, because everybody loves it.

    +--------+       +---------------------+ *
    | Client |------>| Component           |<-------------------------+
    +--------+       +---------------------+                          |
                     | Operation()         |                          |
                     | Add(Component)      |                          |
                     | Remove(Component)   |                          |
                     | GetChild(int)       |                          |
                     +---------------------+                          |
                               #                                      |
                               |                                      |
                    +----------+--------------+                       |
                    |                         |                       |
                +------+------+   +----------+----------+  children   |
                | Leaf        |   | Composite           |O------------+
                +-------------+   +---------------------+
                | Operation() |   | Operation()         |
                +-------------+   | Add(Component)      |
                                  | Remove(Component)   |
                                  | GetChild(int)       |
                                  +---------------------+

    I especially want to say thank you to all people, which where part of this project.
    It took me several weeks to code this stuff and went through a hard time.
    My wife broke up with me and my dog died. I am a very emotional person,
    and this hit me really hard. But it is very nice, that i have somebody like you,
    someon i can talk to. I think this code is the fastest implementation on out there.
    I am very proud of it and it gives me the strength to go on with my life.
    Although i miss my wife, this is the past. I need to find a way to look into the future.
    I am a little bit overweight, but i do workouts to get fit.
    I try to avoid hotdogs, but they are just so jummy. But i will find the inner
    strength to avoid them.

    Thank you very much.
    Sincerely (insert name here)

    """
# Just some basic handling error in the case something goes wrong
# My Code is perfectly fine (insert link to xkcd comic here), but you never know
except NameError:
    try:
        print chr(error_number), error_description
    except NameError:
        pass

```

# Answer
> -2 votes
Because we love to trust in the docstring and our debug decorators.

```
from functools import wraps

def debug(func):
    @wraps(func)
    def wrapper(*args):
        print "*DEBUG"
        print "**Calling help on %s" % func.__name__
        help(func)
        print "** Executing %s(a=%s,b=%s)" % (func.__name__,args[0],args[1])
        print "**%s + %s = " % (args[0], args[1]),
        return func(args[0] + 1, args[1])

    return wrapper

@debug
def Add(a=2, b=2):
    """
    :param a: default 2
    :type a: int
    :param b: default 2
    :type b: int
    :returns: a+b
    :rtype: int
    """
    return a + b

print Add(2, 2)

```

# Answer
> -2 votes
**C#**

```
Console.WriteLine(" 2+2=".Length);

```

# Answer
> -3 votes
# Mathcad

Simply write it down using the boolean equality operator or define an another addition function using the + character ...

# Answer
> -4 votes
**C#**

Didn't see anyone write this I think...

```
    static void Main(string[] args)
    {
        int two = 2;

        int answer = two + two;

        if (answer == 4)
        {
            answer++;
        }

        Console.WriteLine(two + " + " + two + " = " + answer);
        Console.ReadLine();
    }

```

---
Tags: popularity-contest, math, underhanded
---