193
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 11
    \$\begingroup\$ hmmmm.... this one is a brain teaser. +1 \$\endgroup\$ Mar 6, 2014 at 22:30
  • 1
    \$\begingroup\$ Wish 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...) \$\endgroup\$
    – keshlam
    Mar 7, 2014 at 5:43
  • 8
    \$\begingroup\$ I suggest the entire brainfuck language, because BF code just looks like it won't compile. \$\endgroup\$ Mar 10, 2014 at 20:21
  • \$\begingroup\$ @NigelNquande only if you're not familiar with it... ;) \$\endgroup\$
    – Jwosty
    Jun 13, 2014 at 18:25

80 Answers 80

278
votes
\$\begingroup\$

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.

\$\endgroup\$
5
  • 7
    \$\begingroup\$ I feel like the first answer just insta-won this right off the bat. \$\endgroup\$ Mar 7, 2014 at 20:34
  • 1
    \$\begingroup\$ It's also valid in C99. \$\endgroup\$ Mar 9, 2014 at 21:23
  • 1
    \$\begingroup\$ there are warnings with -Wall \$\endgroup\$ Mar 11, 2014 at 9:51
  • 2
    \$\begingroup\$ @BЈовић Wall always throw warning about everything \$\endgroup\$
    – Kiwy
    Mar 13, 2014 at 8:59
  • 4
    \$\begingroup\$ @Kiwy It throws warning only for garbage code like above. The -Wall doesn't throw warnings for everything. \$\endgroup\$ Mar 13, 2014 at 9:01
85
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • 5
    \$\begingroup\$ You got me. I've done both Python and Lua before, and now starting on Ruby. Lua uses that one. \$\endgroup\$
    – Riking
    Mar 7, 2014 at 9:07
  • 7
    \$\begingroup\$ The meaning of the universe is nothing to see? \$\endgroup\$
    – user80551
    Mar 12, 2014 at 15:47
  • 1
    \$\begingroup\$ destroyallsoftware.com/talks/wat \$\endgroup\$ Jun 24, 2014 at 16:07
77
votes
\$\begingroup\$

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.

\$\endgroup\$
7
  • 21
    \$\begingroup\$ So in other words, it's cheating? \$\endgroup\$
    – Mr Lister
    Mar 7, 2014 at 14:33
  • 75
    \$\begingroup\$ Cheating is normal in code-challenge competitions. We call it creativity. :P \$\endgroup\$
    – Joe Z.
    Mar 7, 2014 at 15:42
  • 31
    \$\begingroup\$ 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. \$\endgroup\$
    – Tim S.
    Mar 7, 2014 at 17:11
  • 5
    \$\begingroup\$ It's just supposed to make you stop for a second and go 'hey can you do that?' :) \$\endgroup\$
    – intx13
    Mar 7, 2014 at 18:17
  • 10
    \$\begingroup\$ @JoeZ. It might look like perl in some cases. \$\endgroup\$
    – user80551
    Mar 9, 2014 at 10:01
72
votes
\$\begingroup\$

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").

\$\endgroup\$
12
  • 8
    \$\begingroup\$ This trick can be applied to any languages that accept Unicode token (e.g. Java, C#). \$\endgroup\$ Mar 7, 2014 at 1:59
  • 83
    \$\begingroup\$ @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ , exemplified by your username \$\endgroup\$
    – TheDoctor
    Mar 7, 2014 at 3:03
  • 9
    \$\begingroup\$ too obvious solution \$\endgroup\$ Mar 7, 2014 at 4:35
  • 6
    \$\begingroup\$ too 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. \$\endgroup\$ Mar 7, 2014 at 12:40
  • 42
    \$\begingroup\$ Obvious? 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). \$\endgroup\$
    – Tim S.
    Mar 7, 2014 at 17:06
70
votes
\$\begingroup\$

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().

\$\endgroup\$
6
  • 18
    \$\begingroup\$ As a lua guy, I was expecting 422 \$\endgroup\$
    – mniip
    Mar 7, 2014 at 9:40
  • 3
    \$\begingroup\$ Haven't seen this usage before, very neat. \$\endgroup\$
    – Etheryte
    Mar 9, 2014 at 20:33
  • 5
    \$\begingroup\$ Feel 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 :) \$\endgroup\$ Mar 12, 2014 at 0:31
  • \$\begingroup\$ What does this output ? And why ? I am curious. \$\endgroup\$ Apr 5, 2014 at 8:04
  • 3
    \$\begingroup\$ For 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. \$\endgroup\$
    – Kat
    Jun 8, 2014 at 5:30
62
votes
\$\begingroup\$

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.

\$\endgroup\$
0
54
votes
\$\begingroup\$

Perl

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

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

\$\endgroup\$
4
  • 137
    \$\begingroup\$ Perl programs generally look like errors. \$\endgroup\$
    – ugoren
    Mar 7, 2014 at 17:40
  • 1
    \$\begingroup\$ @ugoren Only when written and read by those with little knowledge of Perl. \$\endgroup\$
    – TLP
    Mar 11, 2014 at 12:11
  • 8
    \$\begingroup\$ You gotta love that @ugoren's comment has twice as many upvotes as the answer :) \$\endgroup\$
    – yo'
    Mar 12, 2014 at 23:54
  • 2
    \$\begingroup\$ Reminds me of the Windows shell trick, "If you're happy and you know it, Syntax Error!" \$\endgroup\$
    – Jwosty
    Jun 22, 2014 at 4:41
46
votes
\$\begingroup\$

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.

\$\endgroup\$
9
  • 3
    \$\begingroup\$ As the question you linked explains, it doesn't run indefinitely, but instead for an extremely long time. \$\endgroup\$
    – Kevin
    Mar 9, 2014 at 7:21
  • 1
    \$\begingroup\$ @Kevin Let's not get unnecessarily pedantic here; "longer than the age of the universe" is, for all practical purposes, "forever". \$\endgroup\$
    – arshajii
    Mar 9, 2014 at 17:52
  • 8
    \$\begingroup\$ You 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. \$\endgroup\$
    – McKay
    Mar 10, 2014 at 14:07
  • \$\begingroup\$ @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. \$\endgroup\$
    – arshajii
    Mar 10, 2014 at 14:22
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – arshajii
    Mar 10, 2014 at 14:27
42
votes
\$\begingroup\$

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.

\$\endgroup\$
36
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 8
    \$\begingroup\$ That's just... wow. \$\endgroup\$
    – primo
    Apr 20, 2014 at 2:26
27
votes
\$\begingroup\$

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

\$\endgroup\$
4
  • 8
    \$\begingroup\$ This should work in any C-like language that supports // comments. \$\endgroup\$ Mar 10, 2014 at 14:32
  • \$\begingroup\$ Yeah, probably, I just wasn't sure while posting \$\endgroup\$
    – Piotr
    Mar 10, 2014 at 21:03
  • 14
    \$\begingroup\$ Limit one URL per protocol per scope, though. \$\endgroup\$
    – Ben Voigt
    Mar 12, 2014 at 17:22
  • 1
    \$\begingroup\$ You still can use https:// in the same scope. \$\endgroup\$
    – Florian F
    Sep 11, 2014 at 20:42
25
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ At Last... Here is the FOO and BAR :) \$\endgroup\$
    – VVK
    Mar 10, 2014 at 10:07
  • 1
    \$\begingroup\$ That's what foo and bar are for ;) names of things that don't actually matter. \$\endgroup\$
    – McKay
    Mar 10, 2014 at 13:49
22
votes
\$\begingroup\$

C

main=195;

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

\$\endgroup\$
11
  • \$\begingroup\$ The opcode for ret is 195, not 193, right? \$\endgroup\$
    – Dennis
    Mar 9, 2014 at 12:41
  • \$\begingroup\$ Doesn't work for me. I'd expect this to execute the code at address 195. \$\endgroup\$
    – nwellnhof
    Mar 9, 2014 at 16:05
  • \$\begingroup\$ Tbanks @Dennis, the code was correct, the explanation wrong. \$\endgroup\$
    – ugoren
    Mar 9, 2014 at 16:41
  • 3
    \$\begingroup\$ On 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)) \$\endgroup\$
    – zwol
    Mar 10, 2014 at 16:29
  • 2
    \$\begingroup\$ I 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. \$\endgroup\$ Mar 16, 2014 at 14:28
21
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 11
    \$\begingroup\$ your varargs are not varargs ;) \$\endgroup\$
    – Navin
    Mar 8, 2014 at 21:04
  • \$\begingroup\$ 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. \$\endgroup\$
    – Nzall
    Mar 10, 2014 at 8:52
  • 19
    \$\begingroup\$ I think you should read the original question again: "or produces some other unrelated error." \$\endgroup\$ Mar 10, 2014 at 8:55
  • \$\begingroup\$ Actually, without the \u000d, it would use a reference to the undefined value a. \$\endgroup\$ Oct 21, 2015 at 19:58
19
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 11
    \$\begingroup\$ Thankfully, 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. \$\endgroup\$
    – hvd
    Mar 8, 2014 at 9:44
16
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 20
    \$\begingroup\$ Just a bonus: print """""""""Python strings don't have to start with the same number of quotes they end with.""""". \$\endgroup\$ Mar 9, 2014 at 9:54
15
votes
\$\begingroup\$

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.

\$\endgroup\$
6
  • 2
    \$\begingroup\$ You should be able to do some tricks with NaN too... \$\endgroup\$
    – intx13
    Mar 7, 2014 at 20:01
  • 8
    \$\begingroup\$ meh, this happens in any language with floats. \$\endgroup\$
    – Navin
    Mar 8, 2014 at 21:01
  • 3
    \$\begingroup\$ @Navin: in any language with floats where division by zero doesn't cause an error. \$\endgroup\$
    – nwk
    Mar 9, 2014 at 20:28
  • 2
    \$\begingroup\$ @nwk The IEEE standard for floats says division by zero must be an inf. I don't know of any languages that change this. \$\endgroup\$
    – Navin
    Mar 10, 2014 at 23:38
  • 1
    \$\begingroup\$ IEEE 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. \$\endgroup\$
    – ulidtko
    Mar 14, 2014 at 11:20
14
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • 12
    \$\begingroup\$ The valid C++ program int main(){(([](){})());} might also look nice when trigraphed... \$\endgroup\$ Mar 7, 2014 at 15:29
  • 1
    \$\begingroup\$ What does that one even do? \$\endgroup\$
    – Joe Z.
    Apr 27, 2014 at 19:56
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – tomsmeding
    Aug 1, 2014 at 8:34
13
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ @minitech Actually, if you pass an empty array to UBound it will give you a Subscript out of range error. \$\endgroup\$
    – Comintern
    Mar 7, 2014 at 5:30
  • \$\begingroup\$ … well. I take that back. VBA =/ \$\endgroup\$
    – Ry-
    Mar 7, 2014 at 5:32
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Comintern
    Mar 7, 2014 at 5:36
12
votes
\$\begingroup\$

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

\$\endgroup\$
3
  • 13
    \$\begingroup\$ How did it happen that you posted exactly the same case as I did an hour after me? \$\endgroup\$
    – VisioN
    Mar 7, 2014 at 11:21
  • 1
    \$\begingroup\$ Hey 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. \$\endgroup\$ Mar 8, 2014 at 15:47
  • 1
    \$\begingroup\$ Sumeet, don't be sorry. Your answer is nicer — and much clearer — than the answer by @VisioN. \$\endgroup\$ Apr 5, 2014 at 8:14
12
votes
\$\begingroup\$

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...

\$\endgroup\$
7
  • 9
    \$\begingroup\$ So 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? \$\endgroup\$
    – VisioN
    Mar 7, 2014 at 13:05
  • 5
    \$\begingroup\$ Yes. Is this cheating? @VisioN \$\endgroup\$
    – Albzi
    Mar 7, 2014 at 13:53
  • 2
    \$\begingroup\$ I'm pretty sure this is cheating. At Least write "HTML" in bold at the top. \$\endgroup\$
    – Navin
    Mar 9, 2014 at 1:42
  • \$\begingroup\$ Nice ! :-) The trick worked on me. \$\endgroup\$ Apr 5, 2014 at 8:17
  • 1
    \$\begingroup\$ I edited to make it clear what language this is written in \$\endgroup\$
    – vijrox
    Jul 22, 2015 at 16:37
9
votes
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ Is there any disadvantage to leaving the bug un-fixed, aside from allowing you to write VBS code that isn't valid in VB6? \$\endgroup\$
    – Gabe
    Mar 8, 2014 at 16:02
  • 1
    \$\begingroup\$ @Gabe: No, there's no downside other than it being harder to port VBScript code to VB. \$\endgroup\$ Mar 8, 2014 at 17:51
  • 1
    \$\begingroup\$ A name ! Who is this news organisation ? \$\endgroup\$ Apr 5, 2014 at 8:26
9
votes
\$\begingroup\$

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).

\$\endgroup\$
3
  • 1
    \$\begingroup\$ As far as I can see, the loop body should never be executed (because 1234 <= 0 evaluates to false). Did you possibly mean to write ">="? \$\endgroup\$
    – celtschk
    Mar 7, 2014 at 21:24
  • 1
    \$\begingroup\$ @celtschk yes, that was a typo. Thanks for noticing! \$\endgroup\$
    – l4mpi
    Mar 7, 2014 at 21:53
  • \$\begingroup\$ Is this memory alignment actually specified, or just implemented this way in some compilers? \$\endgroup\$ Sep 9, 2015 at 21:01
9
votes
\$\begingroup\$

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.

\$\endgroup\$
8
votes
\$\begingroup\$

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).

\$\endgroup\$
4
  • 3
    \$\begingroup\$ This is a popularity contest. No need to cramp up ur code to save bytes. Just reformat it for better readability ;) \$\endgroup\$
    – Songo
    Mar 7, 2014 at 3:31
  • \$\begingroup\$ I will add a readable version later. I used the same exact answer and didn't edited it at all. \$\endgroup\$ Mar 7, 2014 at 10:12
  • \$\begingroup\$ 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. \$\endgroup\$ Mar 8, 2014 at 13:31
  • \$\begingroup\$ Actually, everything play an important role. \$\endgroup\$ Mar 8, 2014 at 17:32
8
votes
\$\begingroup\$

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.

\$\endgroup\$
8
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ So many frowny faces :( \$\endgroup\$
    – Joe Z.
    Apr 27, 2014 at 19:58
8
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Haha, welcome to the site! Kudos for the bravery of this as a first post. :) \$\endgroup\$ Mar 19, 2014 at 14:03
7
votes
\$\begingroup\$

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

\$\endgroup\$
8
  • 1
    \$\begingroup\$ I 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 \$\endgroup\$
    – Jwosty
    Mar 6, 2014 at 23:42
  • \$\begingroup\$ made em more obvious; and spoiler tags are intended cause the tricks arent obvious at first \$\endgroup\$
    – masterX244
    Mar 6, 2014 at 23:56
  • 2
    \$\begingroup\$ Wait, 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? \$\endgroup\$
    – Riking
    Mar 7, 2014 at 9:01
  • 3
    \$\begingroup\$ No java programmer would expect an stack overflow in the second snippet. Sorry, that's by far too obvious. \$\endgroup\$
    – Tobias
    Mar 8, 2014 at 14:39
  • 1
    \$\begingroup\$ @VVK codegolfing habit to use enum{ instead of class{saves a byte then \$\endgroup\$
    – masterX244
    Mar 10, 2014 at 14:52
6
votes
\$\begingroup\$

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);
}
\$\endgroup\$
3
  • 9
    \$\begingroup\$ its hard to read, but i don't know what kind of error people are expecting from this \$\endgroup\$
    – Bryan Chen
    Mar 7, 2014 at 2:40
  • 3
    \$\begingroup\$ I 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). \$\endgroup\$
    – orion
    Mar 7, 2014 at 8:19
  • \$\begingroup\$ Doesn't seem too bad. I've only coded a little in C++, but I can figure this out. \$\endgroup\$
    – Navin
    Mar 9, 2014 at 1:37

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