What? No error?

195

51

Your task is simple. Write a program that should obviously produce an error on first glance either when compiled or run, but either doesn't or produces some other unrelated error. This is a popularity contest, so be creative.

Jwosty

Posted 11 years ago

Reputation: 3 530

Question was closed 9 years ago

11hmmmm.... this one is a brain teaser. +1 – Tim Seguine – 11 years ago

1Wish I could find it... there was an old PL/I example which included a statement along the lines of "if if if = then then then = else else else = if then else ..." (PL/I allowed using its keywords as variable names, and had a conditional expression similar to C's ?: that also used the if/then/else keywords...) – keshlam – 11 years ago

8I suggest the entire brainfuck language, because BF code just looks like it won't compile. – Agi Hammerthief – 11 years ago

@NigelNquande only if you're not familiar with it... ;) – Jwosty – 11 years ago

Answers

280

C++

Make sure you compile the following code in standard conforming mode (for example, for g++ use the -ansi flag):

int main()
{
  // why doesn't the following line give a type mismatch error??/
  return "success!";
}

How it works:

The ??/ is a trigraph sequence that is translated into a backslash which escapes the following newline, so the next line is still part of the comment and therefore won't generate a syntax error. Note that in C++, omitting the return in main is well defined and equivalent to returning 0, indicating a successful run.

celtschk

Posted 11 years ago

Reputation: 4 650

7I feel like the first answer just insta-won this right off the bat. – temporary_user_name – 11 years ago

1It's also valid in C99. – R.. GitHub STOP HELPING ICE – 11 years ago

1there are warnings with -Wall – BЈовић – 11 years ago

2@BЈовић Wall always throw warning about everything – Kiwy – 11 years ago

4@Kiwy It throws warning only for garbage code like above. The -Wall doesn't throw warnings for everything. – BЈовић – 11 years ago

86

Ruby

Always a fan of this one.

x = x

No NameError. x is now nil.

This is just a "feature" of Ruby :-)

Here's a more mundane one that's gotten me before:

x = 42

if x < 0
  raise Exception, "no negatives please"
elseif x == 42
  raise Exception, "ah! the meaning of life"
else  
  p 'nothing to see here...'
end 

Prints "nothing to see here."

It's elsif, not elseif. (and it's certainly not elif - woe to the wayward python programmer (me)!) So to the interpreter elseif looks like a normal method call, and since we don't enter the x<0 block, we go straight on to else and don't raise an exception. This bug is incredibly obvious in any syntax-highlighting environment, thankfully (?) code golf is not such an environment.

roippi

Posted 11 years ago

Reputation: 969

5You got me. I've done both Python and Lua before, and now starting on Ruby. Lua uses that one. – Riking – 11 years ago

7The meaning of the universe is nothing to see? – user80551 – 11 years ago

1http://destroyallsoftware.com/talks/wat – Jakob Weisblat – 11 years ago

77

C?

Pretty normal code here...

void main() = main--;

It's Haskell, not C. It defines a function named "void" that takes two arguments. The first is named "main" and if the second (unnamed) is an empty tuple, it returns the "main" variable. "--" starts a comment in Haskell, so the ";" is commented out.

intx13

Posted 11 years ago

Reputation: 1 517

21So in other words, it's cheating? – Mr Lister – 11 years ago

75Cheating is normal in code-challenge competitions. We call it creativity. :P – Joe Z. – 11 years ago

31

I'd call this one cheating, not creativity. You have to define the environment you're running in before you can even consider whether some code will error or not. Otherwise I could just give you the line noise that is Malbolge and ask you if it compiles.

– Tim S. – 11 years ago

5It's just supposed to make you stop for a second and go 'hey can you do that?' :) – intx13 – 11 years ago

4@TimS. The point is that it looks like C++ but is actually Haskell. Malbolge won't ever look like anything else. – Joe Z. – 11 years ago

10@JoeZ. It might look like perl in some cases. – user80551 – 11 years ago

It would clash with Control.Monad. – PyRulez – 11 years ago

72

JavaScript

var а = 100;
if (typeof a !== 'undefined') throw 'This should always throw, right?';
console.log('How am I still alive?');

Here's how it works:

The first a is actually an а (that is, Cryllic Unicode "a").

Doorknob

Posted 11 years ago

Reputation: 68 138

8This trick can be applied to any languages that accept Unicode token (e.g. Java, C#). – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 11 years ago

83@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ , exemplified by your username – TheDoctor – 11 years ago

9too obvious solution – thepirat000 – 11 years ago

6too obvious for anyone that's come across it before. I'm sure plenty of newbies and so-call "web experts" may get tripped up on it. – Thebluefish – 11 years ago

42Obvious? So you always look at your variable names through their Unicode numbers instead of by what they look like? You might notice it if you search for "a" (or "а"?) and fail to find what you expect, but when simply reading, you can't see it (at least in the font shown here). – Tim S. – 11 years ago

2Copying and pasting tokens from e.g. the OpenGL wiki often does this, since the selection accidentally includes a trailing or leading non-printing character. – imallett – 11 years ago

@IanMallett That caught me with a shader file I was writing last year, made worse by the fact that the IDE I was using (Visual Studio 2010) doesn't do any sort of GLSL syntax checking and automatically saved the file as UTF-8 with BOM, which caused the file as a whole to be rejected by the GLSL parser when compiled. Only when I typed out everything again by hand and still got the error did the possibility of an encoding issue occur to me (I would have thought of it earlier, but for some reason the error wasn't always being marked as occurring at the start of the file, not sure why). – JAB – 11 years ago

@JAB All my shaders are generated at runtime from C++, which I feel makes them more flexible. This has the effect of also avoiding that problem; if the token is unrecognized, it's a compile-time error. – imallett – 11 years ago

@IanMallett A useful methodology, but I was writing it as part of a class project that was an introduction to using shaders and spent a lot of time making the program flexible in other ways and doing more refactoring of the skeleton/shell code we were given that was a port of a C wrapper for OpenGL to make it more C++-style (I'd started on that for previous projects but continued to make adjustments to it), I didn't really have time to set up a proper code generator for the shader code (or the BSP tree I'd wanted to set up, for that matter). – JAB – 11 years ago

1@TimS. Depends on your editor. Mine doesn't render the unicode a for some reason (although it's fine in the browser), so here it would be obvious ;) – Izkata – 11 years ago

Sometimes, with distinct blocks of Unicode covered by visually differing fonts, it's immediately obvious that the characters are not the same. (So I'd rather call this "exploiting glyph mimicry in fonts" than "exploiting Unicode tokens".) So, @TimS, no need for code numbers, just fix your fonts. – ulidtko – 11 years ago

@ulidtko — Fonts giving a sense of harmony in displayed text are not broken. They don't need to be fixed. – Nicolas Barbulesco – 11 years ago

70

JavaScript

When I was providing the following code I was told many times "It must be a typo! How can it work?".

console.log( 42..toString(2) );

The description below was copied exactly from one the recent cases.

As you probably know, in JavaScript everything except literals is an object. Numbers are objects as well. So theoretically (and practically) you may get properties or call methods of any non-literal via dot notation, as you do 'string'.length or [1,2,3].pop(). In case of numbers you may do the same but you should keep in mind that after a single dot the parser will look for a fractional part of the number expecting a float value (as in 123.45). If you use an integer you should "tell" the parser that a fractional part is empty, setting an extra dot before addressing a property: 123..method().

VisioN

Posted 11 years ago

Reputation: 4 490

18As a lua guy, I was expecting 422 – mniip – 11 years ago

3Haven't seen this usage before, very neat. – Nit – 11 years ago

5Feel bad for being perfectly used to the .. notation, but entirely clueless regarding the .toString(a freaking argument here?) notation :P Oh well, figured it out by now :) – David Mulder – 11 years ago

What does this output ? And why ? I am curious. – Nicolas Barbulesco – 11 years ago

@NicolasBarbulesco Give it a try in the browser console and don't forget to read a description in the hidden box. – VisioN – 11 years ago

3For the lazy, the argument specifies the base (so this will print 42 in binary), and is not at all important to this code. .. is the confusing part. – Kat – 11 years ago

62

bash

#!/bin/bash

[ 1 < 2 ] && exit

for i in `seq 1 $[2 ** 64]`
    do "$0" | "$0"
done

while [[ false ]]
    do :
done

if maybe
    do [: [: [: [: [; [; [; [; ;] ;] ;] ;] :] :] :] :]
fi

Results

  • You might expect the script not to produce any errors at all, since it exits after the first command. It doesn't.

  • You might expect the typical error messages caused by an ongoing fork bomb due to the for loop. There's no fork bomb.

  • You might expect bash to complain about the missing maybe command or the whole bunch of syntax error inside the if block. It won't.

  • The only error message the script might produce ends in 2: No such file or directory.

Explanation

  • [ isn't special to bash, so < 2 performs, as usual, redirection. Unless there is a file with name 2 in the current directory, this will cause an error.

  • Due to that error above, the command before && will have a non-zero exit status and exit will not be executed.

  • The for loop isn't infinite. In fact, there's no loop at all. Since bash cannot compute the 64th power of 2, the arithmetic expression's result is 0.

  • [[ false ]] tests if false is a null string. It isn't, so this while loop is infinite.

  • Because of the above, the if statement never gets executed, so no errors get detected.

Dennis

Posted 11 years ago

Reputation: 196 637

55

Perl

use strict;
use warnings;
Syntax error!
exit 0;

Source and explanation: https://stackoverflow.com/questions/11695110

mob

Posted 11 years ago

Reputation: 2 506

137Perl programs generally look like errors. – ugoren – 11 years ago

1@ugoren Only when written and read by those with little knowledge of Perl. – TLP – 11 years ago

8You gotta love that @ugoren's comment has twice as many upvotes as the answer :) – yo' – 11 years ago

2Reminds me of the Windows shell trick, "If you're happy and you know it, Syntax Error!" – Jwosty – 11 years ago

47

Java

class Gotcha {
    public static void main(String... args) {
        try  {
            main();
        } finally {
            main();
        }
    }
}

No stack overflows here; move along.

At first glance, this should produce a StackOverflowError, but it doesn't! It actually just runs forever (for all practical purposes at least; technically it would terminate after a time many orders of magnitude longer than the age of the universe). If you want to know how/why this works, see this. Also, if you happen to be wondering why we can call main() without arguments when the main method generally would need a String[] argument: it's because we've declared it to be variable-argument here, which is perfectly valid.

arshajii

Posted 11 years ago

Reputation: 2 142

it would be nice to see an explanation here and not just a "look it up yourself here" – phil294 – 9 years ago

3As the question you linked explains, it doesn't run indefinitely, but instead for an extremely long time. – Kevin – 11 years ago

1@Kevin Let's not get unnecessarily pedantic here; "longer than the age of the universe" is, for all practical purposes, "forever". – arshajii – 11 years ago

8You say "No stack overflows here", when in fact, the system keeps throwing stack overflows continuously, and will eventually throw a stack overflow exception. (as you mention, eventually could be a very very long time) And, it depends on the stack depth. On a smaller VM, or embedded system, the stack depth could be a lot smaller. – McKay – 11 years ago

@McKay That statement is clearly a mere throwaway line, not meant to be taken literally. The OP asks for a program that looks like it should produce an error, but doesn't. In the general case, the answer above satisfies this requirement. Sure, we can concoct an obscure situation where it doesn't, but that doesn't invalidate the answer. I hope that you will reconsider your downvote. – arshajii – 11 years ago

3@McKay By the way, assume that stack size is small (e.g. 100 as opposed to the normal ~10,000), and we can still make 10,000,000 calls per second. Then the total running time comes out to 4,019,693,684,133,147 years -- still many orders of magnitude larger than the age of the universe. – arshajii – 11 years ago

I'm very familiar with the math involved, but logically, it can be determined what this code will do. And it will theoretically throw a stack overflow exception. But this is [popularity-contest], I personally feel that this goes against the spirit of the competition, so I vote against it. That's my prerogative. – McKay – 11 years ago

@McKay I was just pointing out that the size of the VM is essentially irrelevant here. In any case, I appreciate your taking the time to explain yourself, but we'll have to agree to disagree, I'm afraid! Of course, you are indeed free to vote as you wish in the end. – arshajii – 11 years ago

@arshajii You're clearly an engineer, not a mathematician :) – teh_senaus – 11 years ago

42

CoffeeScript

What? No error? Yep, this code does not have any bugs, why would it?

? followed by a space is operator that calls a function, but only if it exists. JavaScript doesn't have a function called What, therefore the function isn't called, and its arguments are simply ignored. The other words in the code are function calls that actually aren't called, because What function doesn't exist. At end, ? is existence operator, as it is not used in call function. Other sentence enders, such as . or ! would not work, as . is for methods, and ! is not operator (which cannot be used after an identifier). To read how CoffeeScript converted this to JavaScript, visit http://coffeescript.org/#try:What%3F%20No%20error%3F%20Yep%2C%20this%20code%20does%20not%20have%20any%20bugs%2C%20why%20it%20would%3F.

Konrad Borowski

Posted 11 years ago

Reputation: 11 185

36

VBScript

The & operator in VBScript is string concatenation but what on earth are the && and &&& operators? (Recall that the "and" operator in VBScript is And, not &&.)

x = 10&987&&654&&&321

That program fragment is legal VBScript. Why? And what is the value of x?

The lexer breaks this down as x = 10 & 987 & &654& & &321. An integer literal which begins with & is, bizarrely enough, an octal literal. An octal literal which ends with & is, even more bizarrely, a long integer. So the value of x is the concatenation of the decimal values of those four integers: 10987428209.

Eric Lippert

Posted 11 years ago

Reputation: 2 805

8That's just... wow. – primo – 11 years ago

27

Objective-C

Not a big deal, but it has surprised me while trying to put a link inside a comment:

http://www.google.com
        return 42;

http is a code label here, such labels are used in goto instructions

Piotr

Posted 11 years ago

Reputation: 1 321

8This should work in any C-like language that supports // comments. – Ilmari Karonen – 11 years ago

Yeah, probably, I just wasn't sure while posting – Piotr – 11 years ago

14Limit one URL per protocol per scope, though. – Ben Voigt – 11 years ago

1You still can use https:// in the same scope. – Florian F – 10 years ago

25

C#

class Foo
{
    static void Main(string[] args)
    {
        Bar();
    }

    static IEnumerable<object> Bar()
    {
        throw new Exception("I am invincible!");
        yield break;
    }
}

Because the Bar method does a yield, the method doesn't actually run when called, it returns an enumerator which, when iterated,s runs the method.

McKay

Posted 11 years ago

Reputation: 382

At Last... Here is the FOO and BAR :) – VVK – 11 years ago

1That's what foo and bar are for ;) names of things that don't actually matter. – McKay – 11 years ago

22

C

main=195;

Works on x86 platforms, where 195 is the opcode for ret. Does nothing,

ugoren

Posted 11 years ago

Reputation: 16 527

@zwol the behavior is different in C++, any idea what the key differences are? See this SO question. Note, this was recently made ill-formed in C++ and the recent version of gcc and clang make this an error for C++.

– Shafik Yaghmour – 9 years ago

@ShafikYaghmour My best guess is it's not a difference between C and C++, but rather that the person who tested that C++ monstrosity did it on a machine where memory pages can't be readable without also being executable (such as older 32-bit x86) so the data segment is executable. But that's just a guess. I have no deeper insights. – zwol – 9 years ago

@zwol, there is a difference in the specs - C++ is more strict. On the same system where this works in C, it fails to compile as C++ (ISO C++ forbids declaration of main with no type). – ugoren – 9 years ago

@ugoren In C it's still undefined behavior (and has always been). – zwol – 9 years ago

The opcode for ret is 195, not 193, right? – Dennis – 11 years ago

Doesn't work for me. I'd expect this to execute the code at address 195. – nwellnhof – 11 years ago

Tbanks @Dennis, the code was correct, the explanation wrong. – ugoren – 11 years ago

@nwellnhof, it only works on x86, and with compilers such as gcc which don't enforce the rules strictly. On what platform did you try it? – ugoren – 11 years ago

3On any platform (including modern x86) where pages can be readable without also being executable, this will crash upon entry to main because main has been placed in the data segment, which is not executable. Amusingly, const int main=195 will not crash (on x86) (but will produce a garbage exit status) because .rodata by default is put in the same segment as .text and is therefore executable. (const char main[]="1\300\303"; will exit succesfully! (still on x86)) – zwol – 11 years ago

@Zack, You're right - on many x86 systems it won't work. – ugoren – 11 years ago

2I am on a 64bit machine (I don't know if this will change anything) and main=195 gives a segfault, but const int main = 195; works. – w4etwetewtwet – 11 years ago

21

Java

Probably too obvious.

public static void main(String[] varargs) throws Exception{
    char a, b = (char)Integer.parseInt("000d",16);
    // Chars have \u000d as value, so they're equal
    if(a == b){
        throw new Exception("This should be thrown");
    }
}

What?

Throws a syntax error after \u000d. \u000d is the unicode for a new line. Even though it is commented out, the Java compiler treats what is after this as code since it isn't commented out anymore.

Tom Verelst

Posted 11 years ago

Reputation: 321

Actually, without the \u000d, it would use a reference to the undefined value a. – LegionMammal978 – 9 years ago

11your varargs are not varargs ;) – Navin – 11 years ago

The question was "code that looks like it fails but doesn't", not "code that looks that it fails, but does so in a different way". Having a syntax error instead of an exception is still an error. – Nzall – 11 years ago

19I think you should read the original question again: "or produces some other unrelated error." – Tom Verelst – 11 years ago

19

C++

#include <iostream>

int succ(int x)
{
  return x + 1;
}

int succ(double x)
{
  return int(x + 1.0);
}

int succ(int *p)
{
  return *p + 1;
}

int main()
{
  std::cout << succ(NULL) << '\n';
}

Why?

NULL is an intergal constant, so it matches the int overload strictly better than the int* one. Still, most programmers have NULL associated with pointers, so a null pointer dereference can be expected.

Angew is no longer proud of SO

Posted 11 years ago

Reputation: 343

11Thankfully, C++11 allows implementations to define NULL as nullptr, and implementations that do so (none yet that I know of, but I do expect them) will give the expected segmentation fault. – hvd – 11 years ago

16

Python

print """""quintuple-quoted strings!"""""

Perfectly valid, but the output is hard to guess. The first 3 " characters start a multiline string and the next two are part of the string. At the end, the first three "s terminate the string and the last two are an empty string literal that gets concatenated by the parser to the multiline string.

Fraxtil

Posted 11 years ago

Reputation: 2 495

20Just a bonus: print """""""""Python strings don't have to start with the same number of quotes they end with.""""". – Konrad Borowski – 11 years ago

15

JavaScript

if (1/0 === -1/0) {
  throw "Surely there's an error in here somewhere...";
}

How it works:

There's positive and negative infinity in JS, and no error for dividing by zero.

temporary_user_name

Posted 11 years ago

Reputation: 266

2You should be able to do some tricks with NaN too... – intx13 – 11 years ago

8meh, this happens in any language with floats. – Navin – 11 years ago

3@Navin: in any language with floats where division by zero doesn't cause an error. – nwk – 11 years ago

A.k.a. JavaScript. – temporary_user_name – 11 years ago

2@nwk The IEEE standard for floats says division by zero must be an inf. I don't know of any languages that change this. – Navin – 11 years ago

1IEEE 754 specifies two models: signalling NaN/Inf (which raise exceptions on FP zero division, square root from -1, underflow/overflow, etc), and non-signalling (which treats NaN/Inf just like regular argebraic values with well-defined math on them). Modern FP hardware can be configured to operate both ways. Language-agnostic; shame not to know. – ulidtko – 11 years ago

14

C++

Mixing trigraphs and space-less lambdas can be quite confusing and definitely look erroneous to people who are not aware of trigraphs:

int main()
{
    return??-??(??)()??<return"??/x00FF";??>()??(0??);
}

How it works:

Some sequences consisting of 3 symbols, beginning with ??, are called trigraphs and will be substituted by a fully-compliant preprocessor. Preprocessed, the line in question looks as follows: return ~[] (){ return "\x00FF"; }()[0]; As one can see, this is nothing but a superfluous lambda function returning a string consisting of the 0xFFth character. The [0] just extracts that character and ~ NOTs it, so 0 is returned.

aVoX

Posted 11 years ago

Reputation: 141

12The valid C++ program int main(){(([](){})());} might also look nice when trigraphed... – Angew is no longer proud of SO – 11 years ago

1What does that one even do? – Joe Z. – 11 years ago

1@Joe Z [](){} is a lambda function, just like [](int a){return a+1;} is one. ([](){})() calls that function, returning void if I'm not mistaken. The whole (([](){})()); then boils down to (void);, which is a statement doing nothing. main then just returns zero, like it should without a return statement. – tomsmeding – 11 years ago

13

VBA/VB6

Private Sub DivByZero()

    Dim x() As String
    x = Split(vbNullString, ",")

    Debug.Print 1 / UBound(x)

End Sub

Splitting an empty comma delimited string should give an empty array. Should be an obvious division by zero error, right?

Nope. Surprisingly, when any zero length string is split the runtime gives you an array with a lower bound of 0 and an upper bound of -1. The code above will output -1.

Comintern

Posted 11 years ago

Reputation: 3 632

@minitech Actually, if you pass an empty array to UBound it will give you a Subscript out of range error. – Comintern – 11 years ago

… well. I take that back. VBA =/ – Ry- – 11 years ago

1@minitech Yep. I understand this was a bug in the original implementation of Split in VB6. In .NET they intentionally "added" (or maybe documented is the better word) the behavior for empty arrays returning a UBound of -1 in order to maintain backward compatibility with all the VB6 code that took advantage of this hack. Splitting a null string is the only way to natively get this array in VBA/VB6 without Windows API calls. – Comintern – 11 years ago

12

Javascript

5..toString();
5 .toString();

Gives: 5

Whereas:

5.toString();

Gives SyntaxError

How it works:

JavaScript tries to parse dot on a number as a floating point literal

Sumeet Kashyap

Posted 11 years ago

Reputation: 153

13

How did it happen that you posted exactly the same case as I did an hour after me?

– VisioN – 11 years ago

1Hey Vision, sorry but i didn't check your answer. I also added a case with space. I read this once on javascript garden nothing else. – Sumeet Kashyap – 11 years ago

1Sumeet, don't be sorry. Your answer is nicer — and much clearer — than the answer by @VisioN. – Nicolas Barbulesco – 11 years ago

12

HTML

First post here, I'm not sure I get this or not, but here goes.

<html>
    <head></head>
    <body>
        <?php $_POST['non-existant'] = $idontexisteither ?>
    </body>
</html>

It's a .html file...

Albzi

Posted 11 years ago

Reputation: 221

1I edited to make it clear what language this is written in – vijrox – 10 years ago

9So the trick is just that it won't execute the PHP block because the file has .html extension and your web server is not configured to parse .html files as PHP? – VisioN – 11 years ago

5Yes. Is this cheating? @VisioN – Albzi – 11 years ago

2I'm pretty sure this is cheating. At Least write "HTML" in bold at the top. – Navin – 11 years ago

Nice ! :-) The trick worked on me. – Nicolas Barbulesco – 11 years ago

@VisioN — Who did talk of a Web server ? – Nicolas Barbulesco – 11 years ago

Looks like perfectly valid PHP to me. – primo – 11 years ago

9

PHP (40 bytes)

<?for(;;$e.=$e++)foreach($e::$e()as&$e);

This was the answer I gave in this question: Insanity Check Program

The idea was to make a code that produced errors.

The 1st error that we will think of, is a syntax error.

There are no syntax errors...

Other would be that the class/function doesn't exist.

It doesn't run that far...

Other would be a time-out or a memory overflow, but, again, it doesn't reach that far...

Test the code here: http://writecodeonline.com/php/ (remove the <? on the beginning to test).

Ismael Miguel

Posted 11 years ago

Reputation: 6 797

3This is a popularity contest. No need to cramp up ur code to save bytes. Just reformat it for better readability ;) – Songo – 11 years ago

I will add a readable version later. I used the same exact answer and didn't edited it at all. – Ismael Miguel – 11 years ago

foreach(e()as&$e); is the core of this solution. e() is just to keep the syntax-checker going and &$e after the as is what causes the failure. – TheConstructor – 11 years ago

Actually, everything play an important role. – Ismael Miguel – 11 years ago

9

VBScript

Visual Basic 6 users will know that

If Blah Then Foo Bar

is legal, as is

If Blah Then 
    Foo Bar
End If

But what about

If Blah Then Foo Bar End If

? Turns out that is legal in VBScript but not in VB6. Why?

It's a bug in the parser; the intention was to reject this. The code which detects the End If was supposed to also check whether it was a multi-line If statement, and it did not. When I tried to fix it and sent out a beta with the fix, a certain influential industry news organization discovered that they had this line of code in one of their VBScript programs and said they would give the new version a low rating unless we un-fixed the bug, because they didn't want to change their source code.

Eric Lippert

Posted 11 years ago

Reputation: 2 805

Is there any disadvantage to leaving the bug un-fixed, aside from allowing you to write VBS code that isn't valid in VB6? – Gabe – 11 years ago

1@Gabe: No, there's no downside other than it being harder to port VBScript code to VB. – Eric Lippert – 11 years ago

1A name ! Who is this news organisation ? – Nicolas Barbulesco – 11 years ago

9

C

This reminded me of an error I ran into when I learned C. Sadly the original variant doesn't seem to work with a current GCC, but this one still does:

#define ARR_SIZE 1234
int main() {
    int i = ARR_SIZE;
    int arr[ARR_SIZE];
    while(i >= 0) {
        (--i)[arr] = 0;
    }
    i = *(int*)0;
}

This obviously segfaults because we dereference a null pointer, right?

Wrong - actually, it's an infinite loop as our loop condition is off by one. Due to the prefix decrement, i runs from 1023 to -1. This means the assignment overwrites not only all elements in arr, but also the memory location directly before it - which happens to be the place where i is stored. On reaching -1, i overwrites itself with 0 and thus the loop condition is fulfilled again...

This was the original variant I which I can't reproduce anymore:

The same thing worked with i going upwards from 0 and being off by one. The latest GCC always stores i before arr in memory; this must have been different in older versions (maybe depending on declaration order). It was an actual error I produced in one of my first toy programs dealing with arrays.

Also, this one's obvious if you know how pointers work in C, but can be surprising if you don't:

You might think that the assignment to (--i)[arr] throws an error, but it's valid and equivalent to arr[--i]. An expression a[x] is just syntactic sugar for *(a + x) which computes and dereferences the pointer to the indexed element; the addition is of course commutative and thus equivalent to *(x + a).

l4mpi

Posted 11 years ago

Reputation: 191

Is this memory alignment actually specified, or just implemented this way in some compilers? – Paŭlo Ebermann – 9 years ago

1As far as I can see, the loop body should never be executed (because 1234 <= 0 evaluates to false). Did you possibly mean to write ">="? – celtschk – 11 years ago

1@celtschk yes, that was a typo. Thanks for noticing! – l4mpi – 11 years ago

9

Java

public class WhatTheHeckException extends RuntimeException {
    private static double d;        // Uninitialized variable
    public static void main(String... args) {
        if (d/d==d/d) throw new WhatTheHeckException();
        // Well that should always be true right? == is reflexive!

        System.out.println("Nothing to see here...");
    }
}

Why this works:

Unitialized fields have default values. In this case d is just 0. 0/0 = NaN in double division, and NaN never equals itself, so the if returns false. Note this would not work if you had 0/0==0/0, as at would be integer 0/0 division would WOULD throw an ArithmeticException.

durron597

Posted 11 years ago

Reputation: 4 692

8

VBScript

function[:(](["):"]):[:(]=["):"]:
end function
msgbox getref(":(")(":)")

'Output: :)

What it does:

Function, Sub and Variable Names in VBScript can be anything if you use square brackets. This script makes a function called :( and one argument "):" but because they do not follow normal naming convention they are surrounded by square brackets. The return value is set to the parameter value. An additional colon is used to get everything on one line. The Msgbox statement gets a reference to the function (but does not need the brackets) and calls it with a smiley :) as parameter.

AutomatedChaos

Posted 11 years ago

Reputation: 291

1So many frowny faces :( – Joe Z. – 11 years ago

8

C++11

struct comp {
    comp operator compl () { return comp { }; }
    operator comp () { return comp { }; }
    compl comp () { return; comp { }; }
};

int main() {
    comp com;
    compl com;
}

Compiles and runs without any warnings with g++ -pedantic-errors -std=c++11.

compl is a standard alternative spelling for ~, just like not is an alternative for !. compl is used here to first override operator~ and then define a destructor. Another trick is that operator comp is a conversion function from the type comp to itself. Surprisingly the standard does not forbid such a conversion function - but it does say that such a function is never used.

han

Posted 11 years ago

Reputation: 1 226

8

C#

Actually I caught myself on mistakenly doing just that :)

public static object Crash(int i)
{
    if (i > 0)
        return i + 1;
    else
        return new ArgumentOutOfRangeException("i");
}

public static void Main()
{
    Crash(-1);
}

throw, not return.

Spook

Posted 11 years ago

Reputation: 181

Haha, welcome to the site! Kudos for the bravery of this as a first post. :) – Jonathan Van Matre – 11 years ago

7

Java

enum derp
{

    public static void main(String[] a)
    {
        System.out.println(new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point()));
    }
}

And how that one works:

Firs you think the Enum is not valid but its valid; then you think it will print a standard Point objects attributes but Gotcha! due to how Snakeyaml serializes you get a smooth StackOverFLow error

And another one:

enum derp
{

    ;public static void main(String[] a)
    {
        main(a);
    }
    static int x = 1;

    static
    {
        System.exit(x);
    }
}

you think a Stackoverflow will happen due to the obvious recursion but the program abuses the fact that when you run it the static{} block will be executed first and due to that it exits before the main() loads

enum derp
{

    ;
        public static void main(
            String[] a)
    {
        int aa=1;
        int ab=0x000d;
        //setting integer ab to \u000d  /*)
        ab=0;

        /*Error!*/
        aa/=ab;
    }
    static int x = 1;
}

this one relies on that /*Error*/-commented out code as closing point for the comment opened before the ab=0; the explain about the integer ab to 0x000d hides the newline to activate the commentout of the next line

masterX244

Posted 11 years ago

Reputation: 3 942

1I can't right now, but it would be nice if you were to reformat this, if possible. It's a bit hard to read as is... :P – Jwosty – 11 years ago

made em more obvious; and spoiler tags are intended cause the tricks arent obvious at first – masterX244 – 11 years ago

Ah, much better :) – Jwosty – 11 years ago

2Wait, so the first one does, in fact, produce an error? That's the opposite of what the question is asking. And why not just System.exit(1) in the second? – Riking – 11 years ago

you think you get a error in the second due to the obvious recursion; And on the first you dont think that a Stackoverflow is even possible at that spot – masterX244 – 11 years ago

3No java programmer would expect an stack overflow in the second snippet. Sorry, that's by far too obvious. – Tobias – 11 years ago

Hate enums :@ Are they electronic or what ??? – VVK – 11 years ago

1@VVK codegolfing habit to use enum{ instead of class{saves a byte then – masterX244 – 11 years ago

6

C

Strings and arrays in c can be pretty confusing

main(){
  int i=0;
  char string[64]="Hello world;H%s";
  while(strlen(&i++[string])){
    i[' '+string]=string[i]-' ';
  }
  5[string]=44;
  return printf(string,'!'+string);
}

orion

Posted 11 years ago

Reputation: 3 095

9its hard to read, but i don't know what kind of error people are expecting from this – Bryan Chen – 11 years ago

3I just wanted to remind people of valid but unconventional notation - make of it what you will. I would certainly look three times before saying this is valid.

First of all, expressions like 5[string] are not well known to a casual coder and defies logic of array indexing. Secondly, ' '+string looks like addings 2 strings, but with wrong type of quotes. And thirdly, &i++ looks like address of an integer (but the precedence takes care of that). Finally, we are writing beyond the string literal (but not beyond the bigger backing buffer). – orion – 11 years ago

Doesn't seem too bad. I've only coded a little in C++, but I can figure this out. – Navin – 11 years ago

6

Java

  public static void main(String[] args) throws Exception {
        Integer a = 1, b = 1;
        Integer c = 200, d = 200;
        if ( a != b || c == d) {
            throw new Exception("This should be thrown");
        }
    }

The Integers from the range of -127 .. 127 are cached so Integer.valueOf(127) == Integer.valueOf(127) is true but Integer.valueOf(128) == Integer.valueOf(128) is false.

forgacan

Posted 11 years ago

Reputation: 61

Actually, the VM is required to cache the small Integers, but allowed to cache also some bigger ones. So it could actually throw an exception here. – Paŭlo Ebermann – 9 years ago

5

JavaScript

/21 + 21     // SyntaxError in this

SyntaxError could be expected, but this expression works and even returns true.

subzey

Posted 11 years ago

Reputation: 121

Could you explain why it works? – Hjulle – 10 years ago

(new RegExp("21 + 21 ") / SyntaxError) in this. The quotient of a regexp and object is NaN, and NaN in this is true for some reason. – Ming-Tang – 10 years ago

4

python

 = 3

You expect

SyntaxError: unexpected indent

Instead you get

SyntaxError: invalid character in identifier

Also this:

" " == " "
False

Unicode spaces

qwr

Posted 11 years ago

Reputation: 8 929

Isn't it supposed to be IndentationError: unexpected indent? – Oliver Ni – 10 years ago

2I just tried this in python 2.7. The output is different from yours. = 3 -> SyntaxError: invalid syntax, " " == " " -> True – Vader – 11 years ago

4@Vader: NO-BREAK SPACE (U+00A0) will be converted to SPACE (U+0020) on copy/paste under Windows. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 11 years ago

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ that fixes the issue with the ==. The = 3 is still invalid syntax. I am not entirely sure what you are saying but I think you are trying to tell me that because I copied and pasted the = 3 I will not get the desired output. – Vader – 11 years ago

@Vader: I have no idea about the first one. I only comment about the 2nd one. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 11 years ago

9I don't expect SyntaxError: unexpected indent just sayin' – gcq – 11 years ago

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ — The transformation of the non-breaking space into a normal space is due to the Web browser rather than to Windows. – Nicolas Barbulesco – 11 years ago

4

APL

table ← {
  ⍵⍴⍳×/⍵
  [{(]}) ⍝ obviously a syntax error right?
}

Result:

      table 6 8
 1  2  3  4  5  6  7  8
 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48

This does fail:

table ← {
  [{(]})
  ⍵⍴⍳×/⍵
}

But this runs fine again:

table ← {
  0:[{(]})
  ⍵⍴⍳×/⍵
}

APL parsing is lazy. At least in Dyalog APL. (Really!) Also, a d-fn returns the value of the first line that gets a result. ⍵⍴⍳×/⍵ always returns a value (it's not an assignment and it doesn't have a guard), so, ⍵⍴⍳×/⍵ is run and returns a value, and the second line is never even parsed, thus, no error. In the second example, the line [{(]}) is run first, so it fails. But the third example works, because it has a guard (0:), and 0 is false so it's skipped.

marinus

Posted 11 years ago

Reputation: 30 224

6obviously a syntax error Yeah, obviously! – Dennis – 11 years ago

4

Casio Calculator

It's quite hard to count bytes/tokens in this "language" - I've given the number of keypresses required, excluding Shift, Alpha (the second shift key) and = at the end - this certainly fits into 1 byte per keypress.

Tested on the fx-85GT PLUS model, which is a standard, non-graphing, "non-programmable" scientific calculator. Other models will work.

These calculators have two possible input/output formats: MathIO, which is default, and displays expressions as they are written on paper (e.g. fractions display properly), and LineIO, which uses the more conventional method of representing expressions as a single string of characters without vertical dimension - e.g. square root is √(...), fractions are 1⎦2 (that's meant to be like an underscore with a vertical bar of equal length attached to the right, like _| but as a single character).

Code

You'd think that this monstrosity would give many syntax errors. How to enter it:

((.!%PowerNegative-.DegreeRight (close-paren if in linear mode)%Degree

Press = to evaluate it.

What it looks like in linear mode:

((.!%^(--.°)%°

Decimal points without numbers, multiple percent signs, multiple degree signs, too many minuses, unclosed parentheses...

Output

0°0'36"

. evaluates to 0, just as .5 is 0.5 and 5. is 5.
Parentheses are automatically closed at the end of the expression.
((.!%^(--.°) on its own evaluates to 1 - the degree symbol disappears.
Although the calculator uses different symbols for negation and subtraction, the latter can be used for both, while the first only negates. --. is just 0.
Multiple percent symbols can be used in a single number - 1%% evaluates to 0.0001.
Without the final °, the expression evaluates to 0.01.

user16402

Posted 11 years ago

Reputation:

4

C

I don't belive that nobody posted this yet (sorry for archaeology):

const int main[] = {};

C use the same namespace for function names and variable names. So this will compile and link as valid executable but will return SIGSEGV at runtime.

Hauleth

Posted 11 years ago

Reputation: 1 472

2char main[]={0xc3}; compiles, links and executes without any error! You can actually put any valid sequence of opcodes in there, let's say we just want to return 10: char main[]={0xb8,10,0,0,0,0xc3}; – None – 10 years ago

Of course. But I was to lazy to write that. Also your is platform dependent (it will work only on x86 and fail on others). My will do the same on all platforms (will fail) :D – Hauleth – 10 years ago

3

Java (java.util.regex.Pattern)

This post's effectiveness depends on how much you know about Pattern class documentation. The behavior shown below also depends on the quirks in OpenJDK's Java Class Library (JCL) implementation of Pattern class.

  1. Inline flags (valid ones as shown in documentation (?idmsuxU-idmsuxU))

    Pattern.compile("(?t)"); // Throws PatternSyntaxException. Nothing surprising here
    
    Pattern.compile("(?c)"); // Compiles normally (!)
    

    c flag was intended to be used as inline flag for CANON_EQ, but it currently has absolutely no effect, due to the way CANON_EQ is handled.

    There is absolutely no reason to use this in your code.

  2. Character class intersection (shown in documentation as [\p{L}&&[^\p{Lu}]] or [a-z&&[def]], i.e. nesting seems to be required from the example)

    Pattern.compile("[\\p{IsAlphabetic}&&\\pM]"); // Compiled normally (!)
    

    And the compiled Pattern also works when matching against "\u0345".

    However, it is still recommended that you follow the documentation's way of writing regex.

  3. Character class in \p notation (shown in documentation to specify a POSIX character class, a java.lang.Character class, or for Unicode script/block/category/binary property)

    Pattern.compile("\\p{Letter}"); // Throws PatternSyntaxException. Nothing surprising here
    
    Pattern.compile("\\p{all}"); // Both compiles normally (!)
    Pattern.compile("\\p{L1}");
    

    all and L1 are hidden names usable by \p:

    • \p{all} is equivalent to (?s:.).
    • \p{L1} is equivalent to [\x00-\xFF].

    However, since this is not specified in the documentation, I strongly advise you against using them even if you know you can use them.

n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Posted 11 years ago

Reputation: 5 683

3

C++

How many times have you been told to be careful to avoid index out of bounds errors with your for loops?

#include<iostream>
#include<string>
using namespace std;

int main() {
    string s="text here";
    for(int i=0;i<=s.size();i++)
        cout<<s[i];
    return 0;
}

In C++ (and most other languages), strings are just special char-arrays. In C++, a string always has a buffer of a space at the end, which isn't usually noticed because all the functions, etc. account for it. Here I am just accessing the space directly, so it just prints a space instead of crashing with and index out of bounds error.

user10766

Posted 11 years ago

Reputation:

Well, that's rather obvious. Indeed, operator[] doesn't check bounds, unlike at() method. Even if there were no buffer of spaces, you'd not get any error (although it really looks like a UB). – Ruslan – 11 years ago

@Ruslan If I do i<=s.size()+1;, I get an index out of bounds (it compiles, but crashes). Also, if I reference a vector or array this way, it crashes. With those, I have to use the < operator instead. – None – 11 years ago

3Ah, I guess why it doesn't crash here. It's not a buffer of space — it's a zero terminator. That's why it works so only for std::string and only for one single character above maximum. Also, you can't get an exception for operator[] because it doesn't check bounds. You can only get a segfault on "real" out of bounds problem (e.g. with an address sanitizer). – Ruslan – 11 years ago

3

PHP

Some slightly non-standard syntax here:

<html>
<body>
<p>Error?</p>
<?php 

echo beach, far away in time;

?>
<p>What error??</p>

What's going on?

There's a three-per-em space after the opening <?php tag. The PHP parser treats this as part of the tag name, and therefore fails to recognise this code block as PHP. Instead it passes it straight to your web browser. Your browser doesn't understand it either, so all you see is the HTML text that surrounds it. (An ordinary non-breaking space would have worked too, but Markdown converts those to regular spaces so we need to use something different.)

r3mainer

Posted 11 years ago

Reputation: 19 135

3

Python 2

isSorted = lambda a: all(x>y for x,y in zip(a[1:],a[:-1]))
print isSorted( [(1+3j),(1+2j,),(2+1j)] )

The surplus comma after 1+2j does not raise a syntax error, because this is Python’s way of creating a tuple with one element. But most importantly, this avoids that in isSorted complex numbers are compared and thus a TypeError is raised. This is because apart from two complex numbers you can almost compare everything in Python, including complex numbers and tuples.

Wrzlprmft

Posted 11 years ago

Reputation: 2 772

1Nice one, although it only works in python2 as python3 changed the rules for comparisons. – l4mpi – 11 years ago

3

Perl

if (false) {
    # Shouldn't happen
}
else {
    die "Huge error";
}

In Perl, false is not a keyword, and it's parsed a bareword ("false"). As "false" is true, the program exits without any exception (die keyword). Both strict and warnings would notice this problem, which shows why using use strict; use warnings; in Perl is a good idea.

Konrad Borowski

Posted 11 years ago

Reputation: 11 185

3

Java

It is more convoluted than I would like, but here it goes.

package misc;

import java.io.FileWriter;

public class HelloWorld
{
    public static String writeFile(String fileName)
    {
        try {
            FileWriter fw = null;
            try {
                if( fileName==null ) return "bad parameter!";

                fw = new FileWriter(fileName);
                fw.write("Hello, World!\n");
            } finally {
                fw.close();
            }
        } catch( Exception ex ){
        }

        return "OK";
    }

    public static void main(String[] args)
    {
        String result = writeFile("hello.txt"); // returns OK
        System.out.println(result);

        result = writeFile(null); // should return "bad parameter!", right?
        System.out.println(result);
    }
}

The second call to writeFile should complain, right? It doesn't. Both calls return "OK".

If fileName is null, the very first thing the method does is to return an error message. So how can it return "OK"?

The return "bad parameter!"; is executed. But before returning, it has to execute the final section. At that time, fw is null. It throws a NullPointerException and, well, forgets it was supposed to return. The exception is caught and ignored. The procedure returns "OK".

Florian F

Posted 11 years ago

Reputation: 591

1Welcome to the site! Please be sure to add a prominent header to your answers with the language you used. e.g. ## Java as I have added above. – Jonathan Van Matre – 11 years ago

Indeed. Thanks. – Florian F – 11 years ago

3

XML

And you thought you knew XML...

Lo§”“@¥…™¢‰–•~}ñKð}@on%L”…¢¢‡…nÈ…““–k@æ–™“„ZLa”…¢¢‡…n

copy the above in hello.xml and open with IE.

It is encoded in EBCDIC. The XML processor is supposed to detect it. It does in IE. But when you view it, it is usually displayed in UTF or latin, so it is all garbled.

Florian F

Posted 11 years ago

Reputation: 591

It didn't work because of characters getting lost. It is fixed. – Florian F – 11 years ago

After some tests, I see it really works only with IE. And depending how you cut and paste, it might also fail. So I copied the resulting hello.xml on http://florian.net/puzzle/hello.xml

– Florian F – 11 years ago

3

Ruby

1 / 0.0  

This does not result in a ZeroDivisionError, but in

# => Infinity

steenslag

Posted 11 years ago

Reputation: 2 070

FOr everybody that know https://en.wikipedia.org/wiki/IEEE_floating_point it is obvious.

– Hauleth – 9 years ago

3

C#

using System;
class DivideByZero
{
   static int \u004F = Convert.ToInt16('\u0031');

   static void Main(string[] args)
   {
      Console.WriteLine(1 / O);  // Divide by Zero
   }
}

This code is actually dividing by O(the letter) and not 0(the number). If you know your hexadecimal ASCII characters well, then you might notice that I am setting the value of O(the letter) to '1' converted to an int16. Perhaps even weirder to some people, the output of this program is (the number): 0

LVBen

Posted 11 years ago

Reputation: 290

3

REBOL

do not run "this"

How it works:

do: execute the following code.
not: negate.
run: runs the following thing as a bash command.
"this": an illegal bash command, does nothing.

Caridorc

Posted 11 years ago

Reputation: 2 254

2

Ruby

class Foo

  def self.get_bar
    self.bar
  end

  private

  def self.bar
    1 + 1
  end

end

p Foo.bar

Prints 2. Yeah, Ruby just doesn't apply the private modifier to class methods if you declare them this way. If you instead do this in a class << self block it works fine.

histocrat

Posted 11 years ago

Reputation: 20 600

2

Clojure

  (defn check-nil [v] {:pre [nil? v]} v)

  (check-nil nil) 

  (defn check-keyword [v] {:pre [keyword? v]} v)

  (check-keyword “sdf”) 

First one throwing exception but second one does not throw any exception. First one v itself is null that way it throw exception. The form should be {:pre [(nil? v)]} and {:pre [(keyword? v)]}

Mamun

Posted 11 years ago

Reputation: 181

2

Haskell

main=print (0/0, 1/0)

It is funny because Haskell is such a mathematical language, but this won't produce a zero-division error. Instead it outputs (NaN,Infinity). This is because division isn't defined on integer anyways, so it just assumes they are floats, which can be NaN and Infinity.

PyRulez

Posted 11 years ago

Reputation: 6 547

2

C

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

int main(void)
{
    if(1 != 0)
        perror("Error?");

    return 0;
}

perror() produces a message describing the last error encountered during a call to a system or library function - In the absence of an error it will print "Success". As such the output of the program is: "Error?: Success"

JOgden

Posted 11 years ago

Reputation: 451

2

This isn't anything new, but still, the syntax of C/C++ in gcc has always amazed me ;-) Of course, it compiles without any errors by gcc -Wall -pedantic-errors.

#include <ctype.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
    char p = '!';

    switch (argc) {
        while (!isdigit(p))
    case 1:
        p += 1;
        do { break;
    case 2:
        p = '1';
        continue;
    default:
        p = *1[argv];
        } while (false);
    }

    printf("%c\n", p);

    return 0;
}

a[b] is just *(a+b) and cases in switch are just labels. As a bonus, continue works like break here, because the loop checks the condition before jumping. Also, it's nice trick to spell default as defau1t while using a font where 1 and l are hard to distinguish.

:-)

dtldarek

Posted 11 years ago

Reputation: 321

2

#include <stdio.h>

int main(void) {
    if ("hello"=="hello") {
        printf("Same!\n");
    } else {
        printf("Different!\n");
    }
    return 0;
}

Hint:

Oh ho! This is classic CS 101 stuff. Strings should not be compared directly, because they're pointers!


Answer:

. . . except that in this case, since they're the same literal, the compiler has optimized the literals to point to the same location in memory. Hence the output: "Same!\n".

imallett

Posted 11 years ago

Reputation: 995

2

Python

Looks like this should produce an indentation error:

def a():
 print "start"
 if True:
                    for x in range(2):
                     print x 
 if False:
            print "do not print this"

 a()

but it doesn't. And it prints "start" and then 0 and 1.

In fact, Python interpreter doesn't care about the size of indentation, and it is relative to the current block.

sashkello

Posted 11 years ago

Reputation: 121

If I paste this into an interactive python prompt, it actually complains about the wrong indent of the last line (due to the empty line before it the function definition is finished). When I put it into a file and run that, it does nothing (because a is not actually called, the call in the last line is inside the a definition). (Both with Python 2.7.6.) I guess you meant to remove the space in the last line? – Paŭlo Ebermann – 9 years ago

Doesn't look like it to me; people who golf with python would easily recognize this. We often use indentation similarly to this to save characters. – Justin – 11 years ago

1"Looks like this should produce an indentation error" - No, it doesn't. At least, not to me. – glglgl – 11 years ago

2

Haskell

{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}

import Control.Monad

main = 0 -- just bogus value so we can compile and see if the below definitions make sense...
         -- will be an error if you actually try to run this as a program.

data Complex a = Complex { realPart :: a, imagPart :: a }

instance Monad Complex where  -- to get convenience functions `liftM` etc..
  return x = Complex x x
  Complex r i >>= f = f r

instance (Monad complex, Num a) => Num (complex a) where
                            -- allow `Complex` to be used with numerical operators
  fromInteger = return . fromInteger
  (+) = liftM2(+)
  (*) = liftM2(*)
  abs = liftM abs
  signum = liftM signum

instance (Monad Complex, Fractional a) => Fractional (Complex a) where
  fromRational = return . fromRational
  (/) = liftM2(/)

Indeed, it's normally not possible to define an effectful action such as main by simply writing = number. If you try to run main = 0 alone, it'll sure enough give an error (indeed at compile time already).
However, I made a mistake further down in the code: the Num (complex a) instance should have Complex in uppercase like everywhere else. But it's lowercase, so the compiler will interpret this as a type variable and define a Num instance not only for Complex, but for all Monad types. This includes particularly the IO monad, so all of the sudden the definition of main on top makes sense: 0 is now an acceptable value, and will simply be wrapped up and returned.

ceased to turn counterclockwis

Posted 11 years ago

Reputation: 5 200

2

JavaScript

var bSum = function (result, current, index, source) {
    return  result + (current << ( soucre.length - index - 1))
}
[1,0,1,0,1,0].reduce (bSum,0) //42

This obviously fails with a ReferenceError: soucre is not defined right?

Nope,
because of the function expression, there is no ASI, and the ArrayLiteral becomes a Property Accesor. Since the function has no property 0. The above fails even before, throwing a
TypeError: Cannot call method 'reduce' of undefined

C5H8NNaO4

Posted 11 years ago

Reputation: 1 340

What is an ASI? – celtschk – 11 years ago

@celtschk Automatic Semicolon Insertion

– C5H8NNaO4 – 11 years ago

2

Bit late on this one, but whatever.

PHP

<?='this ';</script>is some<%echo('code');

outputs "this is some code" (at least on my system)

PHP allows <script>...</script> and <%...%> alongside <?php...?>, <?...?>, and <?=...?> for enclosing tags for reasons nobody quite understands, allows mixing of these tags in a single script (in this example, <?=...</script> for reasons nobody quite understands, and doesn't actually require a closing tag for reasons nobody quite understands. As such, this is actually two separate code segments (<?='this ';</script> and <%echo('code');), with is some just being garbage.

Tortoise

Posted 11 years ago

Reputation: 224

2

C++

Two plus two is minus four.

#include <cassert>

int main() {
  struct {
    int two : 2;
  } _;
  _.two = 2;

  assert(_.two + _.two == -4);

  return 0;
}

Returns successfully; there is no error. http://ideone.com/eHQcJQ

This is actually quite a useful (but dangerous) feature - controlled overflow of a limited size bitfield struct member.

Riot

Posted 11 years ago

Reputation: 4 639

2

JavaScript

As you've seen, using 99999.toString() gives an error, where 99999..toString() works.

Now, have a look at this code:

0322323022302343534534535043.toString()

The number here is an octal (base-8) number. The octal notation does not have decimals in JavaScript.

user2428118

Posted 11 years ago

Reputation: 2 000

2

Javascript

a = 1
a+++1

Javascript now has a triple plus operator

Zero Fiber

Posted 11 years ago

Reputation: 640

(a++)+1. Outputs a+1 // 0 then adds 1 to a. – Jamie – 10 years ago

2

Go

package main insofaras
import "fmt" notwithstanding
func whereas main() {
    fmt despiteallobjections.Println(
        thetruthofthematter "Hello, world!")
}

http://golang.org/src/cmd/gc/lex.c defines some strange keywords like despiteallobjections, which are ignored by the language.

Konrad Borowski

Posted 11 years ago

Reputation: 11 185

1

Python

I made this mistake when I started coding in python. So, I guess its worth telling

a=b=[1,2,3]
b.append(1)
print(a[3])

It seems like it will produce IndexError: list index out of range right?

But, It won't! actually a,b both points to the same list so whatever we do with b will change the list. So we will see 1 as output

Having said that, lets see another example:

a=b=[1,2,3]  
b=[1,2,3,1]  
print(a[3])

You might expect to see 1 as output. But, you won't! Here things are different. Now, after b=[1,2,3,1] , b points to a completely different list. So, the first list remain unchanged and thus we get the IndexError: list index out of range

Wasi

Posted 11 years ago

Reputation: 1 682

Knowing that lists are almost always implemented using pointers, I wouldn't expect at all the second example t o work. – H2CO3 – 11 years ago

@H2CO3 Neither do I. Actually i wanted to put it inside the spoiler tag to show it as an example but NOT as another answer. But, I couldn't use spoiler tag on the code block. – Wasi – 11 years ago

1-1 huh? no surprises here – wim – 11 years ago

1

JavaScript:

function isInputValid(value) {
    return +value === 0;
}

if (!isInputValid(' \n')) throw 'Invalid input';

What happens is that the + unary operator tries to convert the operand to a number - and for some bizarre reason, any string containing only white-space is converted to 0.


if ('Test' === new String('Test')) throw 'The strings are equal';

The === operator compares the references, and the primitive string 'Test' is not equal to an instance of a String object; therefore, it doesn't throw any error.

Toothbrush

Posted 11 years ago

Reputation: 3 197

String('Test') isn't an String instance , it's just 'Test'. I guess you meant new String('Test') – Oriol – 11 years ago

1

JavaScript

  • Code 1:

    (function() {
        return
        {
            error: undeclaredVariable
        };
    })();
    
  • Code 2:

    (function() {
        return
        {
            error: undeclaredVariable,
            foo: 'bar'
        };
    })();
    

It seems both should throw ReferenceError: undeclaredVariable is not defined, but:

  • The first one doesn't throw any error
  • The second one throws SyntaxError: missing ; before statement

That's because JavaScript doesn't require ; at the end of lines, so a return followed by line break exits function without returning following object.

Oriol

Posted 11 years ago

Reputation: 792

1

Python:

@type
@type
def f(x):
    return 0/0
f(0)(0)

f(anything)(object) returns type(object).

People tend to forget that decoraters don't always do what they seem to do ;)

ɐɔıʇǝɥʇuʎs

Posted 11 years ago

Reputation: 4 449

1

Java

No error for any input, and the curly brackets don't even match

public class ShouldFail {

    public static void main(String[] args) {
        String secret = "v#19!e/\u0022;}/*sd@x";
        if (!secret.equals(args[0]))
            throw new RuntimeException("Invalid argument");
        }
        System.out.println("***/// argument is valid ///***"); 

}

\u0022 ends the string, the rest of the program is enclosed in /* comments */

Cephalopod

Posted 11 years ago

Reputation: 575

What do we learn: don't copy+paste arbitrary data into string literals (or comments, either). – Paŭlo Ebermann – 9 years ago

How does this...? – HyperNeutrino – 9 years ago

1

HTML/PHP

 <?php

   echo '<pre>';
   print_r($_POST);
   echo '</pre>';

    ?>
        <form action="dummy.php" method="post">
        <dl> 
            <dd>select months</dd>
            <dt><select id="month" name="month" size="6" multiple="multiple">
                <option>January</option>
                <option>February</option>
                <option>March</option>
                <option>April</option>
                <option>May</option>
                <option>June</option>
                <option>July</option>
                <option>August</option>
                <option>September</option>
                <option>October</option>
                <option>November</option>
                <option>December</option>
            </select>
            </dt>                

            <dd></dd>
            <dt><input name="submit" id="submit" type="submit" value="submit"/>
        </dl>
        </form> 

You can select multiple months by holding down the shift key or ctrl key. You'd expect all selected options to arrive in $_POST after hitting the submit button.
Well...
Only one, no matter how many you pick.
NO error message, neither PHP nor HTML.

select id="month" name="month" size="6" multiple="multiple"
is the problem – PHP assigns them all into the same variable, so only the last of them survives.

name="month[]" instead of name="month" does the trick (now they become all entries in an array).

Tina

Posted 11 years ago

Reputation: 11

1

Emacs Lisp

It looks like there should be a divide by 0 error but there is not! (evals to 0)

(when (= 0 (- ? ? ))
  (print "(- ? ? ) does equal zero!")
  ;; look! no divide by 0 error!
  (/ 1 (- ? ? ))) 

chars in emacs lisp are written: '?{character}' so ?a in emacs lisp == 'a' in C. The bad part about this is that a ? followed by a space character is a valid way of writing ' '. This works with anywhite space character though. In the first (- ? ? ) I am doing space minus space which is 32 - 32 == 0. In the second (- ? ? ), the second whitespace character is actually the unicode char #x2001. so it is not 0

Jordon Biondo

Posted 11 years ago

Reputation: 1 030

1

    public static void main(String[] args) {
    try{
        int a[] = new int[2];
        System.out.println("Accessing out of bounds :" + a[3]);
    }catch(NullPointerException e){
        System.out.println("But we dont catch out of bounds exceptions  :" + e);
    } finally {
        return;
    }
}

finally is always guaranteed to run

softarn

Posted 11 years ago

Reputation: 111

1

C

Here's another one:

#include <stdio.h>

int main()
{
  int a[2] = { 2, 6 };
  int typo = 2;

  /* Calculate a[1]/a[0] + typo
     to save a character (code golf!), write *a instead of a[0] */
  int r = a[1]/*a + tipo;
  /* the above should trigger an error because I wrote tipo instead
     of typo; why does it compile correctly? */

  -1; /* statement with no effect, but no warning about this? */

  printf("%d\n", r); /* and this even prints the correct value! */
  return 0;
}

Explanation:

The / from the intended division and the * from the intended pointer dereference together form the comment starter /*. Note that inside the comment, further /* are not parsed, so the comment continues until the end of the intended statement. Of course, due to thwe unintentionally long comment, the -0; is no longer a separate statement, but gets part of the previous definition, to form the complete definition int r = a[1] - 1. Due to the carefully chosen constants, this gives the same result as a[1]/a[0] + typo. However, when compiling using gcc with warnings on, you do get a warning of the nested /* (and another one about the unused typo variable).

celtschk

Posted 11 years ago

Reputation: 4 650

1

Brainfuck

Of course, this varies by interpreter, but it fails to run on mine:

Author: Darkgamma (contact: darkgamma@email(dot)com)    

>++++++++[<++++++++>-]<++++++++.>+++++[<+++++>-]
<++++.>+++[<+++>-]<--..+++.>+++++++++[<---------
>-]<++.>+++++++[<+++++++>-]<++++++.>+++++[<+++++
>-]<-.+++.>++[<-->-]<--.>+++[<--->-]<+.>++++++++
[<-------->-]<---.

In Brainfuck, all text (save for the eight commands) is taken as a comment. So what's at play here? The trick's in the fact that some interpreters take "@" as end-of-source and stop interpreting after that point. Doesn't work on all interpreters but stumped me on mine until I figured out what was going on.

Darkgamma

Posted 11 years ago

Reputation: 181

1

static void Main(string[] args)
    {
        object foo = 10;
        object bar = 10;

        if (foo == bar)
            throw new Exception("They're equal!");

        Console.WriteLine("Why am I here? Obviously {0} == {1}, right?", foo, bar);
        Console.ReadLine();
    }

Output:

Why am I here? Obviously 10 == 10, right?

The == operator compares the references of the two objects, not the unboxed value. The code above would throw an exception if it was "if (foo.Equals(bar))" instead

UbbeLoL

Posted 11 years ago

Reputation: 51

Which language is this supposed to be? – Paŭlo Ebermann – 9 years ago

1@PaŭloEbermann I think JavaScript. – ASCIIThenANSI – 9 years ago

1

T-SQL

select CustomerID 
from NorthWind.dbo.Customers 
where not exists (select DivideByZero=1/0
                    ,BadConversion=convert(int,'xxx')
                    ,InvalidParameter=left('abc',-ShipVia)
                    ,DateOverflow=dateadd(year,9999,getdate())
                    ,ArithmeticOverflow=cast(1e308 as tinyint)
                    ,InvalidCursorRef=cursor_status('junk','junk')
                    ,BadSubquery=(select top (-OrderID) EmployeeID 
                                  from NorthWind.dbo.Employees)
              from NorthWind.dbo.Orders 
              where CustomerID=Customers.CustomerID)

This should have a lot of errors (named in the query), but because it's a subquery in an exists clause, it runs without error. Taken from http://bradsruminations.blogspot.com/2009/09/age-old-select-vs-select-1-debate.html.

bmarks

Posted 11 years ago

Reputation: 2 114

1

JavaScript

Disturbing string to boolean conversion

booleanValue = Boolean("false");
if(!booleanValue){
    throw "I threw an error!"
}

Mario Trucco

Posted 11 years ago

Reputation: 251

0

Whoops! I'm such a n00b, I thought I could just paste a url right into the source code ..

int main()
{
  http://codegolf.stackexchange.com/
  printf("My first C program\n");
  return 0;
}

wim

Posted 11 years ago

Reputation: 585

2

Dup of http://codegolf.stackexchange.com/a/23453/6638

– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 11 years ago

0

Java

public static void main(String[] args) {
     http://codegolf.stackexchange.com/questions/23250/what-no-error
}

http: is a label, the rest of the line is commented out

Cephalopod

Posted 11 years ago

Reputation: 575

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, but without operator :) – Qwertiy – 9 years ago

@Qwertiy: Not sure what you are talking about. It's still the trick with comment and label. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 9 years ago

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ That is a weird username... – HyperNeutrino – 9 years ago

3

Dup of http://codegolf.stackexchange.com/a/23453/6638

– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 11 years ago

0

Python

#i don't think theres a module called antigravity..../
import antigravity

There's an easter egg in python.. im not going to tell u what it does

Maltysen

Posted 11 years ago

Reputation: 59

I guess anyone knowing python knows that there are many modules one doesn't know. – Paŭlo Ebermann – 9 years ago

Who can figure it out first? – Maltysen – 11 years ago

0

C

#include <stdio.h>

int g(int a) {
    return a + 1;
}

int f(int a) {
    g(a);
    return;
}

int main() {
    printf("%d\n", f(13));
}

f has to return an int, but returns void. This actually is an error and undefined behaviour, but with GCC on linux, this will work, since the return value of g will still be in place when control returns from f. This may - however - not be the case on any system.

urzeit

Posted 11 years ago

Reputation: 1 297

This looks like a bug in the compiler. – Nicolas Barbulesco – 11 years ago

0

In AppleScript

item -1 of {1,2}

  →  Expected error : AppleScript error : Impossible to get item -1 of {1, 2}.

  →  Actual result : 2

The negative number -1 has a special handling. This trick works even further :

item -2 of {1,2}

  →  Actual result : 1

But :

item 0 of {1,2}

  →  Actual result : AppleScript error : Impossible to get item 0 of {1, 2}.

Nicolas Barbulesco

Posted 11 years ago

Reputation: 249

0

AWK

This program works like cat utility in UNIX.

AWK! Run a program that works exactly like cat

Running (in shell):

awk 'AWK! Run a program that works exactly like cat' list of files (or nothing for STDIN)

Nothing in AWK is a concatentation operator, accessing unknown variables returns empty string, ! operator when seeing nothing returns 1. Contatenation of "AWK" variable and boolean inverse of concatenation of lots of strings gives 1 (think, $AWK + !($Run + $a + $program + ...)). AWK is line based, so 1 is taken as a condition in condition { code } block. Code block is optional, and when not specified, it prints the input line.

Konrad Borowski

Posted 11 years ago

Reputation: 11 185

0

C or C++

Based on celtschk's answer:-

int main (int argc, char *argv [])
{
  return argc ["success!"];
}

(yes, I have done that in production code, mainly to ensure people had read the code)

Skizz

Posted 11 years ago

Reputation: 2 225

Note to self: read other answers before posting – Skizz – 10 years ago