[Question]
  [
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
 
 
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
 
 
Write a snippet, a function, a programm, ... that is obfuscated in a way that it looks clear at the first sight that it does something else.
For example: write a bit of code that adds two number, but when you ask someone "what does it do?", he will tell you it prints "Hello, World!".
**Rules**
* The code must be readable for someone who roughly knows the language you use (avoid intrinsic obfuscated language like APL, in your own interest).
* The code must do something unexpected that the reader initially couldn't predict.
* When you ask different readers, they must have the same (wrong) opinion about what the code does.
**Rating**
* Please read other contestants' codes during maximum 10-20 seconds, just to have a good idea of what happens there.
* Add a comment to the answer saying what you *think* the code does. If the answer you want to give is already there, simply *+1* the comment. (if you miss that answer and add another comment, don't worry, it won't be counted as another answer).
* The points will be awared this way: (`maxFalseOpinion` - `goodGuess`) / `totalOpinion` (see example below).
* **Rate other contestants with fairplay** and don't comment your own code.
* Only add useful comments. Avoid "I don't know" and "good one!", they are not taken into account for the rating, but it's the code and not the ratings that must be obfuscated.
**Rating example**
The snippet adds two numbers. The comments say:
(3) It displays "Hello, World!"  
(1) It substracts 2 numbers.  
(2) It adds 2 numbers.
The total amount of points is the maximum number of opinions (3) - the number of good guesses (2) divided by the total amount of guesses (3 + 1 + 2 = 6). Result: (3 - 2) / 6 = 1/6 = **16.67%**.
---
**MORE ABOUT POINTS**
People seem to have some trouble figuring out the points.
Here is a perfect score:
```
printf('Hello World');
```
*comments:*  
It displays the number of time you have clicked a button. (17 comments).  
TOTAL: 17 comments
Score: (17 - 0)/17 = 1 = 100%
Here is a lame score:
```
printf('Hello World');
```
*comments:*  
It prints "Hello World". (13 comments).  
TOTAL: 13 comments
Score: (0 - 13) / 13 = -1 = -100%
Here is a not so bad score:
```
printf('Hello World');
```
*comments:*  
It prints the user name. (2 comments).  
It displays the current time (15 comments).  
It returns what you entered without modification. (3 comment).  
It prints "Hello World" (1 comment).  
TOTAL: 21 comments
Score: (15 - 1) / 21 = 0.6667 = 66.67%  
Explaining :  
15 is the main guess, what people said the most.
1 is the correct number of guesses.
21 is the sum of all comments.
  
[Answer]
## Javascript
```
var а;
a = 1;
а++;
alert( a );
```
Answer: **It outputs `1`.** The comments below explain it pretty well - there are two different variables here, [a - 'LATIN SMALL LETTER A'](http://www.fileformat.info/info/unicode/char/61/index.htm) and [а - 'CYRILLIC SMALL LETTER A'](http://www.fileformat.info/info/unicode/char/430/index.htm).
There was **1** correct answer, **50** people thought it outputs 2, and with a total of **52** answers, the score is (50 - 1) / 52 = 49 / 52 = **94,23%**
[Answer]
## C, Score 33.3%
```
#include <stdio.h>
int main(int ac, char **av) {
        const char *arg = av[1];
        #define valid_ch(ch) (ch!='&' && ch!='\\')  // All valid except & and \
        while (*arg)
        {
                if (valid_ch(*arg)) putchar(*arg);
                arg++;
        }
        puts("");
        return 0;
}
```
Run `./prog 'Hello & goodbye, world!'`
## Score
The correct answer is `H\n` (the `while` is part of the comment, thanks to the line ending with `\`, so there's no loop), given by 6 people.  
The most popular mistake was `Hello goodbye, world\n`, given by 25 people.  
(25 - 6) / 57 = 33.3%.  
Thanks to Olivier Dulac for bothering to calculate.
[Answer]
# Python
```
a = []
for i in range(10):
    a.append(i * ++i)
for a[i] in a: 
    print(a[i])
```
**Rating**
1. **Good answer:** Prints `0
1
4
9
16
25
36
49
64
64`, each number on one line.
2. **Explanation:** Despite nobody getting the right answer, I consider this mostly a failed attempt, because nobody made the mistake I had intended. (I'll add a real explanation later if nobody else does.)
3. Number of good answers: 0
4. Number of peoply with same wrong answer: 7
5. Total number of answers: 11
6. **Score:** 63,64 % (rounded to two decimals)
## Explanation
First, a list `a` is created and filled with values `i * ++i`. There is no `++` operator in Python, but there is a unary `+` operator, which does nothing for integers, and applying it two times still does nothing. So `a` contains the squares of the integers from `0` to `9`.
I had put the `++` as a distraction and hoped that most voters would go on, thinking they had found the trap, and fall into the real trap. It didn't work out. Some thought that `++` is a syntax error, and the others still looked for the trap. 
**The trap**
The trap was in the second for loop:
```
for a[i] in a: 
    print(a[i])
```
I was sure that most people would think this prints out all the `a[i]`, i.e. `0 1 4 9 16 25 36 49 64 81`, each number on one line. That's what you get with this variaton, for example:
```
for x in a: 
    print(x)
```
`x` is assigned the values in `a`, and then `x` is printed. In the first version, `a[i]` is assigned the values in `a`, and then `a[i]` is printed. The difference is, that in our case we have `i == 9`, and thus the value of `a[9]` is changed each time through the loop. When finally `a[9]` is printed, it has the value of `a[8]`, and thus `64` is printed again. 
[Answer]
**JavaScript**, Score of **-100%**
I did not invent this, [Gary Bernhardt did](https://www.destroyallsoftware.com/talks/wat) but it is one of my favourites
```
alert(Array(16).join("wat?" - 1)+", BATMAN!")
```
[Answer]
# Python, -54.8%
Answer: Raises `SyntaxError: not a chance`
```
from __future__ import braces
if (input() > 0) {
print 'You entered a positive number';
}
else {
print 'You didn\'t enter a positive number';
}
```
* Good guesses: 24
* Same bad guesses: 7
* Total guesses: 31
Explanation:
`from __future__ import braces` is one of the easter eggs in Python. It is meant as a joke, saying that Python will never use braces for scoping in the future.
[Answer]
# Perl, 26.67%
**Results:**
**This prints "I am ambivalent about saying anything at all."**
`my $num1,$num2 = @_;` is missing parentheses. Therefore, it is equivalent to `my $num1; $num2 = @_;`. `$num1` doesn't get set to anything. 
Thus `$num1` is never greater than zero. The bit about the secret fish world hidden off the screen is, err, a red herring, so that people think they have found the "trick".
Furthermore, the ternary operator is an l-value in Perl: `1 ? $a = 1 : $b = 2` actually means `(1 ? $a = 1 : $b) = 2`. Which means `($a = 1) = 2` is evaluated, setting `$a` to `2`. Contrary to appearances, The second string is assigned to `$num1`.
In case you are wondering,`//` is the defined-or operator. If the sub returned an undefined value, the string `"Stuff did not happen."` would be printed. But it doesn't actually happen. It was just to give people another option.
**Scoring:**
Total correct: 5
Total guesses: 30
Score: (13 - 5) / 30 = 26.67%
```
no warnings;
no strict;
no feature;
no 5.16;
no Carp;
sub do_mysterious_stuff
{
    my $num1,$num2 = @_;               
    if ($num1 > 0)
    {                                                                                                                  eval q; $num1="This is a secret fish world. Carp cannot be repressed!" or
       $num1 = "Hello, world!";
    }
    else
    {
        $num2 > 0 ? 
            $num1 = "What's up, world?": 
            $num2 = "I am ambivalent about saying anything at all.";
    }
    return $num1;
}
print do_mysterious_stuff(1,1) //"Stuff did not happen.";
```
[Answer]
## **PHP** 52%
```
  $arg = 'T';
  $vehicle = ( ( $arg == 'B' ) ? 'bus' :
               ( $arg == 'A' ) ? 'airplane' :
               ( $arg == 'T' ) ? 'train' :
               ( $arg == 'C' ) ? 'car' :
               ( $arg == 'H' ) ? 'horse' :
               'feet' );
  echo $vehicle;
```
(Copied verbatim from [here](http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/))
**Explanation & Score**
> 
>  The correct answer is **horse**. This isn't a trick or sleight of hand. Bizarrely, this is how the ternary operator is defined in PHP.  
> 
> **3** chose the correct answer: **horse**,  
> 
> **16** people chose **train** which is correct in literally every other language ever invented, except PHP.  
> 
> **25** answers total, giving a score of (16 - 3) / 25 = 52%
> 
> 
> 
[Answer]
# C++ 28.9%
```
#include <iostream>
using namespace std;
void print( void ) {
  static int times = 0;
  
  switch( times ) {
  case 0:
     cout << "Hello";
     break;
  case 1:
     cout << "World";
     break;
  default:
     cout << "Goodbye";
     break;
  }
  times++;
}
int main(int cout, char* argv[]) {
  
  print();
  cout << '\n';
  print();
}
```
## Solution
> 
>  The point of this code is to trick the user into thinking that a newline character will be printed between the text "Hello" and "World". Notice that the first parameter to main is named cout. Since, in the scope of main, cout is an integer, the << operator actually performs a left shift operation with a parameter of '\n', rather than printing a newline.
>  The print function is there mainly to take attention away from the input parameters in main, but also to allow std::cout to be used without adding the namespace prefix.
> 
> 
> 
## Score
Courtesy of Alvin Wong
* Total 38 answers:
* 12 thought `HelloWorld` (considering minitech's and zeel's are the same)
* 23 thought `Hello\nworld` 3 thought something else.
* Score is (23 - 12) / 38 = **28.9%**
[Answer]
# Ruby, 100%
```
display = lambda { puts "Hello, world!" }
display()
```
Correct answer:
> 
>  Prints "main" with no newline. Explanation: In Ruby, you can't call a lambda using the normal parentheses syntax. Instead, display() is interpreted as the built-in method all objects have: o.display prints o.to\_s to standard output. Methods called without an object are interpreted as methods of "main", an Object that includes the Kernel module.
> 
> 
> 
Score: 3 of the same wrong answer, no other answers.
[Answer]
# Python, -28.13%
```
x = 0
while x < 10:
    if (x%2)==0: x += 2
else: x += 1
print x
```
---
This prints `11` because the `else` block, which belongs to the `while`, is executed after the loop is exited.
* Maximum number of false guesses: 8
* Correct guesses: 17
* Total guesses: 8 + 17 + 7 = 32
Score: (8 - 17) / 32 = -28.13%
[Answer]
## Python: Rating: -27%
```
name = "Robin"
seek = "Seek and find holy grail"
favorite_color = "blue"
from os import *
print "What is your name: %s" % name
print "What is your quest: %s" % seek
print "What is your favorite color: %s" % favorite_color
```
The program prints: 
```
What is your name: <value of os.name> 
What is your quest: Seek and find holy grail
What is your favorite color: blue
```
Rating:
Total opinions: 22
12 correct
3 + 1 + 6 wrong [for Bakuiru's answer, I would say it was close but still incorrect as os.name is a string (os.uname is a function)]
Rating based on that assumption and my understanding of the rating system: 
 Maximum wrong = 6
 Correct = 12
 Score = (6-12)/22 = -27%
[Answer]
Python
```
import sys
class TwoPlusTwoIsFive(object):
  def __bool__(self):
    if 2 + 2 == 5:
      return True
    else:
      return False
two_plus_two_is_five = TwoPlusTwoIsFive()
if two_plus_two_is_five:
  print('{} is company'.format(sys.version[0]))
else:
  print('{} is a crowd'.format(sys.version[0]))
```
---
edit: 
score (8-1)/9 == 77.7 %
correct output is '2 is company' on python 2, '3 is a crowd' on python 3. 
[Answer]
## JavaScript, -46.7%
```
var getResult = function(n, notReadyYet) {
    alert("Calculating results...");
    if (notReadyYet) {
        setTimeout(getResult, 100, n);
    } else {
        sayResult(n);
    }
    return arguments.callee;
}
var sayResult = function(n) {
    if (n >= 10) {
        alert("That's a big number!");
    }
    if (n < 10) {
        alert("That's a small number.");
    }
    return n;
}
(function() {
    var input = parseInt(prompt("Please enter a number:"));
    var result = getResult(input, true);
    return result;
})();
```
You can run it [here](http://jsfiddle.net/grc4/u97Ng/2/) when you're ready (have a guess first!). If you scroll down far enough in the JS panel, you will see the code with a brief explanation.
Correct answer:
> 
>  After asking the user to enter a number, it will enter into an infinite loop and display "Calculating results..." alerts until the maximum call stack size is exceeded (although the jsfiddle example will stop after about 20 times). However, if a semicolon is placed after the closing brace of the sayResult function, it will work as mgibsonbr described in the comments.
> 
> 
> 
Scoring:
* Good answers: 9
* Most popular false opinion: 2
* Total answers: 15
[Answer]
## Javascript
```
var a = [];
a.push( "Hello" );
a.concat( [ ", ", "world", "!" ] );
alert( a.join("") )
```
Answer: **It alerts `Hello`**. The [`concat` method](http://msdn.microsoft.com/en-us/library/ie/2e06zxh0%28v=vs.94%29.aspx) does not modify the array - it *returns* an array which contains the concatenation of the array it's called on and any other supplied arguments. 
**15** correct, **26** wrong, **41** answers in total and the score is (26-15) / 41 = 11 / 41 = **26,83%** 
[Answer]
## Python 33.3%
```
def Test():
    False = True
    True = False
    if False:
        return False
    elif True:
        return True
    else:
        return None
a = Test()
print a
```
Note: Assume this is Python 2.x, and not Python 3.
---
When run, this code produced an `UnboundLocalError: local variable 'True' referenced before assignment`.
[Answer]
**Java**
```
public class Puzzle {
    public static void main(String[] args) {
        String out = "Some ungodly gibberish";
        //char x = \u000a; out = out + " and then some more. ";
        System.out.println(out);
    }
}
```
First attempt at codegolf...
good answer: Prints `Some ungodly gibberish and then some more.` and a newline
Rating: 
* Maximum number of guesses 6
* Total number of guesses 11
* number of correct guesses 5 (0 if you're in pedanitc mode)
Score: 9% (55% in pedantic mode)
[Answer]
**C# 62.5%**
```
int sum=0;
List<Task> threads = new List<Task>();
for (int i=1; i<=10; i++) {
  Task adder = new Task( ()=> sum += i );
  threads.Add( adder );
  adder.Start();
}
foreach (var t in threads ) { 
  t.Wait();
}
Console.WriteLine("Sum of all numbers in 1..10 is: "+sum);
```
This is my first code golf.
The correct answer was: "something between 55 and 110". That's because whenever the "sum+=i" statement executes, it'll use the current value of i. This code might even execute *after the for loop is done*, at which point i has value 11. This makes the highest-possible value 110 (and you can make sure to see it if you slow down the lambda in your testing). The smallest possible value is sum(1..10), which is 55.
* Good answers: 0
* Only approximately good answers: 5
* Number of times the most popular answer was selected: 5
* Total answers: 8
score: strictly speaking, no one got it right so the score should be (5-0)/8=**62.5%.**
If we're willing to count "approximately good" as a correct answer, then the score is (5-5)/8=0% 
[Answer]
# Python, -83.3%
Answer: Prints `a < b` if the inputs are equal, `a = b` if the first is larger, and `a > b` if the second is larger.
```
a = input()
b = input()
print 'a', '<=>'[cmp(a, b)], 'b'
```
* Good guesses: 11
* Same bad guesses: 1
* Total guesses: 12
Explanation:
`cmp(a, b)` returns `0` if both arguments are equal, `1` if the first is larger, and `-1` if the first is smaller, which is why the wrong comparison symbol is printed.
[Answer]
## PHP, 100%
First time posting to code gulf, hopefully this isn't to bad.
```
function word_to_num($word) {
 switch ($word) {
  case "one":
   return 1;
  case "two":
   return 2;
  case "three":
   return 3;
  default:
   return "error";
 }
}
function print_word($num) {
 switch ($num) {
  case 1:
   print "hello";
   break;
  case 2:
   print "world";
   break;
  case "error":
  default:
   print " ";
  }
}
$words = array("one", 0, "two");
foreach ($words as $word) {
 $result = word_to_num($word);
 print_word($result);
}
```
---
correct output is 'hellohelloworld'
score is (10 - 0) / 10 = 1 = 100%
[Answer]
## Perl: 100% (4-0)/4
```
print (1 + 2) * 3, "\n"; 
#
```
This program prints "3" without a new line. Perl parses this instruction as
```
((print (1+2)) * 3, "\n")
```
so only the `(1+2)` is passed as an argument to `print`.
[Answer]
**C#**
```
static void Main(string[] args)
{
     Console.WriteLine('H' + 'e' + 'l' + 'l' + 'o');
     Console.ReadLine();
}
```
[Answer]
CPython 
```
if 'Hello' + 'World' is 'HelloWorld':
  print 'Hello'
if 'Hello' + 'World!' is 'HelloWorld!':
  print 'World!'
```
---
correct output is 'Hello'
score (14-3)/19 == 57.9 %
[Answer]
# C (Score: 4.45%)
Good guesses: 7  
Maximum of wrong guesses: 6+2 = 8  
Total guesses: 6+7+3+2+4=22
**Solution:** `??/` is a trigraph for `\`, so the newline is escaped and the `scanf` line is commented out. Therefore the program runs forever, printing `Guess a number between 1 and 10:`. The comments are a quote from Mozart (via `fortune`).
```
// Why not?/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// What?/
int main(int argc, char** argv)
{
    // Why not?/
    int number;
    // Why should I not send it?/
    srand(time(NULL));
    while(1)
    {
        // Why should I not dispatch it?/
        printf("Guess a number between 1 and 10: ");
        // Why not??/
        scanf("%d", &number);
        // Strange! I don't know why I shouldn't/
        if(number == rand() % 10 + 1)
        {
            // Well, then/
            printf("You guessed right!\n");
            // You will do me this favor./
            exit(0);
        }
    }
}
```
Spoiler, how to compile and run:
> 
>  gcc test.c -trigraphs
> 
> 
> 
[Answer]
# Java
```
public class Test {
    public static void main(String[] args) {
        String fmt = "%s - %04d\n";
        System.out.println(fmt.format("Padded value: ", 0x0c));
    }
}
```
## The Answer
It prints `Padded value:` (with a newline).
String's `format` method is `static`, with the format being passed as the first parameter. I.e. the call above is equivalent to:
```
        System.out.println(String.format("Padded value: ", 0x0c));
```
Number of good answers: 2
Wrong answers: 9
**Score**: (9-2) / 11 = 63%
[Answer]
**C**
```
#include <stdio.h>
#define SIX  1+5
#define NINE 8+1
int main()
{
    printf("%d\n", SIX * NINE);
}
```
Score = (3-16)/19 == -68.4%
Don't forget your towel.
[Answer]
# C++
```
#include <cstdio>
int main()
{
    int f;
    
    f or (f = 0, f < 1000, ++f,
        printf("H ello world !\n"));
    return 0;
}
```
### Score = (1 - 6) / 7 = -0.71428571428571 = -71.428571428571%
[Answer]
**JavaScript**
```
var x = 0;
var y = !x * 4;
var z = !y;
alert("Z = "+z);
```
[Answer]
Python
```
def greeting():
  try:
    return 'Hello World'
  finally:
    return 'HELL0 W0RLD'
print greeting().lower()
```
correct output is 'hell0 w0rld'
score (8-14)/22 == -27.3 % 
[Answer]
## R: 100%
Not that imaginative but might puzzle some people:
```
sum(data.frame(rep(1,10),stringAsFactors=TRUE))
```
What do you think is the result?
**Edit**:
The answer was 20. Because of a missing `s` in `stringAsFactors` (instead of `stringsAsFactors`), the argument is not recognized so the function create a new column called `stringAsFactors`. Because of vector recycling, the column contains 10 times `TRUE` which are converted to `1`s in the sum, hence a total of 20 and not 10.
This answer was not given in the comments.
3 answers were given (all saying `10` more or less). Hence a score of an 100%, I guess.
[Answer]
## Tcl
Inspired by [ugoren](https://codegolf.stackexchange.com/a/11446/7789)
```
foreach c [split [lindex $argv 0] {}] {
    # Don't print the invalid chars & and \
    if {$c in "& \\"} {continue}
    puts -nonewline $c
}
```
Sorry, forgot an example string. Ok, run as 
> 
> ./charfilter.tcl 'Hello & goodbye, world!'
> 
> 
> 
**Edit**
Right solution: It does not filter at all. (**6x**)  
Max wrong answer: **4x**  
Total answers: **10**  
Score: **-0.2**
]