What? No error?

198

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 2014-03-06T22:25:01.220

Reputation: 2 332

Question was closed 2016-01-22T23:33:36.347

11hmmmm.... this one is a brain teaser. +1 – Tim Seguine – 2014-03-06T22:30:01.887

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 – 2014-03-07T05:43:35.937

8I suggest the entire brainfuck language, because BF code just looks like it won't compile. – Agi Hammerthief – 2014-03-10T20:21:55.053

@NigelNquande only if you're not familiar with it... ;) – Jwosty – 2014-06-13T18:25:26.597

Answers

284

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 2014-03-06T22:25:01.220

Reputation: 4 212

7I feel like the first answer just insta-won this right off the bat. – Aerovistae – 2014-03-07T20:34:01.537

1It's also valid in C99. – R.. – 2014-03-09T21:23:18.657

1there are warnings with -Wall – BЈовић – 2014-03-11T09:51:54.487

2@BЈовић Wall always throw warning about everything – Kiwy – 2014-03-13T08:59:17.020

4@Kiwy It throws warning only for garbage code like above. The -Wall doesn't throw warnings for everything. – BЈовић – 2014-03-13T09:01:20.257

87

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 2014-03-06T22:25:01.220

Reputation: 979

5You got me. I've done both Python and Lua before, and now starting on Ruby. Lua uses that one. – Riking – 2014-03-07T09:07:55.840

7The meaning of the universe is nothing to see? – user80551 – 2014-03-12T15:47:27.147

1http://destroyallsoftware.com/talks/wat – Jakob Weisblat – 2014-06-24T16:07:28.987

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 2014-03-06T22:25:01.220

Reputation: 1 517

21So in other words, it's cheating? – Mr Lister – 2014-03-07T14:33:50.200

75Cheating is normal in code-challenge competitions. We call it creativity. :P – Joe Z. – 2014-03-07T15:42:31.967

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. – 2014-03-07T17:11:01.490

5It's just supposed to make you stop for a second and go 'hey can you do that?' :) – intx13 – 2014-03-07T18:17:48.290

4@TimS. The point is that it looks like C++ but is actually Haskell. Malbolge won't ever look like anything else. – Joe Z. – 2014-03-08T23:19:12.980

10@JoeZ. It might look like perl in some cases. – user80551 – 2014-03-09T10:01:47.663

It would clash with Control.Monad. – PyRulez – 2014-04-20T21:13:15.573

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 2014-03-06T22:25:01.220

Reputation: 49 044

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

83@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ , exemplified by your username – TheDoctor – 2014-03-07T03:03:10.783

9too obvious solution – thepirat000 – 2014-03-07T04:35:53.890

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 – 2014-03-07T12:40:00.190

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. – 2014-03-07T17:06:07.393

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 – 2014-03-10T04:30:24.777

@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 – 2014-03-10T15:41:51.793

@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 – 2014-03-10T15:59:46.453

@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 – 2014-03-10T16:15:00.153

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 – 2014-03-10T18:41:15.327

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 – 2014-03-14T10:32:06.553

@ulidtko — Fonts giving a sense of harmony in displayed text are not broken. They don't need to be fixed. – Nicolas Barbulesco – 2014-04-05T08:00:10.327

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 2014-03-06T22:25:01.220

Reputation: 4 375

18As a lua guy, I was expecting 422 – mniip – 2014-03-07T09:40:02.520

3Haven't seen this usage before, very neat. – Nit – 2014-03-09T20:33:38.743

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 – 2014-03-12T00:31:15.363

What does this output ? And why ? I am curious. – Nicolas Barbulesco – 2014-04-05T08:04:42.633

@NicolasBarbulesco Give it a try in the browser console and don't forget to read a description in the hidden box. – VisioN – 2014-04-05T10:02:43.380

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 – 2014-06-08T05:30:22.973

63

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 2014-03-06T22:25:01.220

Reputation: 171 923

55

Perl

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

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

mob

Posted 2014-03-06T22:25:01.220

Reputation: 2 326

137Perl programs generally look like errors. – ugoren – 2014-03-07T17:40:04.960

1@ugoren Only when written and read by those with little knowledge of Perl. – TLP – 2014-03-11T12:11:47.167

8You gotta love that @ugoren's comment has twice as many upvotes as the answer :) – yo' – 2014-03-12T23:54:30.367

2Reminds me of the Windows shell trick, "If you're happy and you know it, Syntax Error!" – Jwosty – 2014-06-22T04:41:46.507

48

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 2014-03-06T22:25:01.220

Reputation: 1 959

it would be nice to see an explanation here and not just a "look it up yourself here" – Blauhirn – 2016-01-03T19:50:13.843

3As the question you linked explains, it doesn't run indefinitely, but instead for an extremely long time. – Kevin – 2014-03-09T07:21:22.540

1@Kevin Let's not get unnecessarily pedantic here; "longer than the age of the universe" is, for all practical purposes, "forever". – arshajii – 2014-03-09T17:52:48.477

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 – 2014-03-10T14:07:34.160

@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 – 2014-03-10T14:22:12.373

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 – 2014-03-10T14:27:42.817

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 – 2014-03-10T20:21:25.820

@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 – 2014-03-10T20:32:18.810

@arshajii You're clearly an engineer, not a mathematician :) – teh_senaus – 2014-03-13T10:37:01.513

43

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.

xfix

Posted 2014-03-06T22:25:01.220

Reputation: 9 392

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 2014-03-06T22:25:01.220

Reputation: 2 835

8That's just... wow. – primo – 2014-04-20T02:26:50.793

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 2014-03-06T22:25:01.220

Reputation: 1 321

8This should work in any C-like language that supports // comments. – Ilmari Karonen – 2014-03-10T14:32:19.073

Yeah, probably, I just wasn't sure while posting – Piotr – 2014-03-10T21:03:45.137

14Limit one URL per protocol per scope, though. – Ben Voigt – 2014-03-12T17:22:07.127

1You still can use https:// in the same scope. – Florian F – 2014-09-11T20:42:48.427

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 2014-03-06T22:25:01.220

Reputation: 402

At Last... Here is the FOO and BAR :) – VVK – 2014-03-10T10:07:47.700

1That's what foo and bar are for ;) names of things that don't actually matter. – McKay – 2014-03-10T13:49:35.100

22

C

main=195;

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

ugoren

Posted 2014-03-06T22:25:01.220

Reputation: 15 019

@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 – 2015-09-30T20:29:44.557

@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 – 2015-09-30T21:27:14.763

@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 – 2015-10-01T06:46:45.213

@ugoren In C it's still undefined behavior (and has always been). – zwol – 2015-10-01T16:06:18.507

The opcode for ret is 195, not 193, right? – Dennis – 2014-03-09T12:41:47.527

Doesn't work for me. I'd expect this to execute the code at address 195. – nwellnhof – 2014-03-09T16:05:56.503

Tbanks @Dennis, the code was correct, the explanation wrong. – ugoren – 2014-03-09T16:41:17.277

@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 – 2014-03-09T16:42:07.390

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 – 2014-03-10T16:29:48.723

@Zack, You're right - on many x86 systems it won't work. – ugoren – 2014-03-10T21:38:47.207

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 – 2014-03-16T14:28:53.487

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 2014-03-06T22:25:01.220

Reputation: 321

Actually, without the \u000d, it would use a reference to the undefined value a. – LegionMammal978 – 2015-10-21T19:58:39.427

11your varargs are not varargs ;) – Navin – 2014-03-08T21:04:05.523

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 – 2014-03-10T08:52:11.910

19I think you should read the original question again: "or produces some other unrelated error." – Tom Verelst – 2014-03-10T08:55:03.237

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

Posted 2014-03-06T22:25:01.220

Reputation: 341

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 – 2014-03-08T09:44:03.670

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 2014-03-06T22:25:01.220

Reputation: 2 195

20Just a bonus: print """""""""Python strings don't have to start with the same number of quotes they end with.""""". – xfix – 2014-03-09T09:54:01.110

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.

Aerovistae

Posted 2014-03-06T22:25:01.220

Reputation: 266

2You should be able to do some tricks with NaN too... – intx13 – 2014-03-07T20:01:53.873

8meh, this happens in any language with floats. – Navin – 2014-03-08T21:01:42.373

3@Navin: in any language with floats where division by zero doesn't cause an error. – nwk – 2014-03-09T20:28:37.363

A.k.a. JavaScript. – Aerovistae – 2014-03-10T14:39:56.823

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 – 2014-03-10T23:38:57.930

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 – 2014-03-14T11:20:56.830

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 2014-03-06T22:25:01.220

Reputation: 141

12The valid C++ program int main(){(([](){})());} might also look nice when trigraphed... – Angew – 2014-03-07T15:29:56.880

1What does that one even do? – Joe Z. – 2014-04-27T19:56:27.373

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 – 2014-08-01T08:34:12.563

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 2014-03-06T22:25:01.220

Reputation: 3 437

@minitech Actually, if you pass an empty array to UBound it will give you a Subscript out of range error. – Comintern – 2014-03-07T05:30:45.113

… well. I take that back. VBA =/ – Ryan – 2014-03-07T05:32:04.243

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 – 2014-03-07T05:36:04.400

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 2014-03-06T22:25:01.220

Reputation: 153

13

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

– VisioN – 2014-03-07T11:21:58.943

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 – 2014-03-08T15:47:28.163

1Sumeet, don't be sorry. Your answer is nicer — and much clearer — than the answer by @VisioN. – Nicolas Barbulesco – 2014-04-05T08:14:14.810

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 2014-03-06T22:25:01.220

Reputation: 221

1I edited to make it clear what language this is written in – vijrox – 2015-07-22T16:37:23.933

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 – 2014-03-07T13:05:56.250

5Yes. Is this cheating? @VisioN – Albzi – 2014-03-07T13:53:34.140

2I'm pretty sure this is cheating. At Least write "HTML" in bold at the top. – Navin – 2014-03-09T01:42:03.883

Nice ! :-) The trick worked on me. – Nicolas Barbulesco – 2014-04-05T08:17:22.220

@VisioN — Who did talk of a Web server ? – Nicolas Barbulesco – 2014-04-05T08:18:52.120

Looks like perfectly valid PHP to me. – primo – 2014-04-20T02:25:49.210

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 2014-03-06T22:25:01.220

Reputation: 5 787

3This is a popularity contest. No need to cramp up ur code to save bytes. Just reformat it for better readability ;) – Songo – 2014-03-07T03:31:20.137

I will add a readable version later. I used the same exact answer and didn't edited it at all. – Ismael Miguel – 2014-03-07T10:12:57.920

foreach(e()as&amp;$e); is the core of this solution. e() is just to keep the syntax-checker going and &amp;$e after the as is what causes the failure. – TheConstructor – 2014-03-08T13:31:53.790

Actually, everything play an important role. – Ismael Miguel – 2014-03-08T17:32:16.957

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 2014-03-06T22:25:01.220

Reputation: 2 835

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 – 2014-03-08T16:02:51.207

1@Gabe: No, there's no downside other than it being harder to port VBScript code to VB. – Eric Lippert – 2014-03-08T17:51:11.863

1A name ! Who is this news organisation ? – Nicolas Barbulesco – 2014-04-05T08:26:06.163

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 2014-03-06T22:25:01.220

Reputation: 191

Is this memory alignment actually specified, or just implemented this way in some compilers? – Paŭlo Ebermann – 2015-09-09T21:01:01.123

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 – 2014-03-07T21:24:18.177

1@celtschk yes, that was a typo. Thanks for noticing! – l4mpi – 2014-03-07T21:53:09.750

+1 for stack munging. – imallett – 2014-03-10T04:57:18.807

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 2014-03-06T22:25:01.220

Reputation: 3 316

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 2014-03-06T22:25:01.220

Reputation: 291

1So many frowny faces :( – Joe Z. – 2014-04-27T19:58:01.323

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 2014-03-06T22:25:01.220

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 2014-03-06T22:25:01.220

Reputation: 181

Haha, welcome to the site! Kudos for the bravery of this as a first post. :) – Jonathan Van Matre – 2014-03-19T14:03:32.850

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 2014-03-06T22:25:01.220

Reputation: 3 346

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 – 2014-03-06T23:42:36.960

made em more obvious; and spoiler tags are intended cause the tricks arent obvious at first – masterX244 – 2014-03-06T23:56:05.573

Ah, much better :) – Jwosty – 2014-03-06T23:58:11.427

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 – 2014-03-07T09:01:27.397

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 – 2014-03-07T10:18:43.443

3No java programmer would expect an stack overflow in the second snippet. Sorry, that's by far too obvious. – still_learning – 2014-03-08T14:39:26.867

Hate enums :@ Are they electronic or what ??? – VVK – 2014-03-10T10:06:29.540

1@VVK codegolfing habit to use enum{ instead of class{saves a byte then – masterX244 – 2014-03-10T14:52:16.747

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 2014-03-06T22:25:01.220

Reputation: 2 690

9its hard to read, but i don't know what kind of error people are expecting from this – Bryan Chen – 2014-03-07T02:40:13.900

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 – 2014-03-07T08:19:19.990

Doesn't seem too bad. I've only coded a little in C++, but I can figure this out. – Navin – 2014-03-09T01:37:48.650

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 2014-03-06T22:25:01.220

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 – 2015-09-09T21:09:24.130

5

JavaScript

/21 + 21     // SyntaxError in this

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

subzey

Posted 2014-03-06T22:25:01.220

Reputation: 121

Could you explain why it works? – Hjulle – 2015-03-05T19:27:08.107

(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 – 2015-03-07T03:52:12.213

5

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 2014-03-06T22:25:01.220

Reputation: 1 221

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}; – Alessandro – 2015-02-06T15:25:57.087

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 – 2015-02-06T16:14:51.700

4

python

 = 3

You expect

SyntaxError: unexpected indent

Instead you get

SyntaxError: invalid character in identifier

Also this:

" " == " "
False

Unicode spaces

qwr

Posted 2014-03-06T22:25:01.220

Reputation: 4 855

Isn't it supposed to be IndentationError: unexpected indent? – Oliver Ni – 2015-01-02T04:17:07.517

2I just tried this in python 2.7. The output is different from yours. = 3 -> SyntaxError: invalid syntax, " " == " " -> True – Vader – 2014-03-07T01:59:12.033

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

@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 – 2014-03-07T02:07:12.630

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

9I don't expect SyntaxError: unexpected indent just sayin' – gcq – 2014-03-07T15:13:39.067

@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 – 2014-04-05T21:00:36.840

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 2014-03-06T22:25:01.220

Reputation: 29 024

6obviously a syntax error Yeah, obviously! – Dennis – 2014-03-09T18:43:51.430

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.

professorfish

Posted 2014-03-06T22:25:01.220

Reputation: 6 031

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 2014-03-06T22:25:01.220

Reputation: 5 161

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.

Hosch250

Posted 2014-03-06T22:25:01.220

Reputation: 505

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 – 2014-03-07T09:31:52.003

@Ruslan If I do i&lt;=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 &lt; operator instead. – Hosch250 – 2014-03-07T16:31:34.777

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 – 2014-03-07T20:13:24.243

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

squeamish ossifrage

Posted 2014-03-06T22:25:01.220

Reputation: 17 888

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 2014-03-06T22:25:01.220

Reputation: 2 199

1Nice one, although it only works in python2 as python3 changed the rules for comparisons. – l4mpi – 2014-03-07T18:58:53.387

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.

xfix

Posted 2014-03-06T22:25:01.220

Reputation: 9 392

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 2014-03-06T22:25:01.220

Reputation: 561

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 – 2014-03-15T00:18:02.270

Indeed. Thanks. – Florian F – 2014-03-15T10:39:00.087

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 2014-03-06T22:25:01.220

Reputation: 561

It didn't work because of characters getting lost. It is fixed. – Florian F – 2014-03-17T13:00:07.637

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 – 2014-03-17T22:58:53.687

3

Ruby

1 / 0.0  

This does not result in a ZeroDivisionError, but in

# => Infinity

steenslag

Posted 2014-03-06T22:25:01.220

Reputation: 1 672

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

– Hauleth – 2015-09-07T07:35:19.623

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 2014-03-06T22:25:01.220

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 2014-03-06T22:25:01.220

Reputation: 1 319

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 2014-03-06T22:25:01.220

Reputation: 18 102

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 2014-03-06T22:25:01.220

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 2014-03-06T22:25:01.220

Reputation: 3 162

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 2014-03-06T22:25:01.220

Reputation: 451

2

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 2014-03-06T22:25:01.220

Reputation: 4 355

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 2014-03-06T22:25:01.220

Reputation: 311

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 2014-03-06T22:25:01.220

Reputation: 790

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 2014-03-06T22:25:01.220

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 – 2015-09-09T21:17:36.010

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 – 2014-03-13T00:15:42.667

1"Looks like this should produce an indentation error" - No, it doesn't. At least, not to me. – glglgl – 2014-03-14T14:31:22.777

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 2014-03-06T22:25:01.220

Reputation: 5 000

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 2014-03-06T22:25:01.220

Reputation: 1 311

What is an ASI? – celtschk – 2014-03-23T16:11:25.230

@celtschk Automatic Semicolon Insertion

– C5H8NNaO4 – 2014-03-23T16:32:29.237

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 2014-03-06T22:25:01.220

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 2014-03-06T22:25:01.220

Reputation: 4 599

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 2014-03-06T22:25:01.220

Reputation: 1 275

2

Javascript

a = 1
a+++1

Javascript now has a triple plus operator

Sampriti Panda

Posted 2014-03-06T22:25:01.220

Reputation: 620

(a++)+1. Outputs a+1 // 0 then adds 1 to a. – Jamie – 2015-02-22T13:03:33.673

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.

xfix

Posted 2014-03-06T22:25:01.220

Reputation: 9 392

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 2014-03-06T22:25:01.220

Reputation: 1 422

Knowing that lists are almost always implemented using pointers, I wouldn't expect at all the second example t o work. – H2CO3 – 2014-03-07T19:05:22.073

@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 – 2014-03-07T19:59:21.337

1-1 huh? no surprises here – wim – 2014-03-12T00:00:34.157

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 2014-03-06T22:25:01.220

Reputation: 3 087

String('Test') isn't an String instance , it's just 'Test'. I guess you meant new String('Test') – Oriol – 2014-03-13T01:03:55.010

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 2014-03-06T22:25:01.220

Reputation: 782

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 2014-03-06T22:25:01.220

Reputation: 545

What do we learn: don't copy+paste arbitrary data into string literals (or comments, either). – Paŭlo Ebermann – 2015-09-09T21:19:52.373

How does this...? – HyperNeutrino – 2015-09-12T21:20:33.863

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 2014-03-06T22:25:01.220

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 2014-03-06T22:25:01.220

Reputation: 960

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 2014-03-06T22:25:01.220

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 2014-03-06T22:25:01.220

Reputation: 4 212

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 2014-03-06T22:25:01.220

Reputation: 171

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 2014-03-06T22:25:01.220

Reputation: 51

Which language is this supposed to be? – Paŭlo Ebermann – 2015-09-09T21:41:55.903

1@PaŭloEbermann I think JavaScript. – ASCIIThenANSI – 2015-09-24T19:08:09.750

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 2014-03-06T22:25:01.220

Reputation: 2 104

1

JavaScript

Disturbing string to boolean conversion

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

Mario Trucco

Posted 2014-03-06T22:25:01.220

Reputation: 231

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 2014-03-06T22:25:01.220

Reputation: 400

2

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

– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-12T10:27:51.513

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 2014-03-06T22:25:01.220

Reputation: 545

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, but without operator :) – Qwertiy – 2015-09-06T20:16:58.903

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

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ That is a weird username... – HyperNeutrino – 2015-09-12T21:27:00.350

3

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

– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-12T10:27:19.570

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 2014-03-06T22:25:01.220

Reputation: 61

I guess anyone knowing python knows that there are many modules one doesn't know. – Paŭlo Ebermann – 2015-09-09T21:37:47.523

Who can figure it out first? – Maltysen – 2014-04-04T02:07:47.847

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 2014-03-06T22:25:01.220

Reputation: 1 287

This looks like a bug in the compiler. – Nicolas Barbulesco – 2014-04-05T21:27:29.070

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 2014-03-06T22:25:01.220

Reputation: 259

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.

xfix

Posted 2014-03-06T22:25:01.220

Reputation: 9 392

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 2014-03-06T22:25:01.220

Reputation: 2 175

Note to self: read other answers before posting – Skizz – 2015-07-22T18:12:44.350

-1

Here's an odd C quirk:

int main()
{
    int x = x;
}

It's more fun in C++ if you do something horrible like replace int with a class that has a copy constructor. (bonus points for no other constructors)

Hurkyl

Posted 2014-03-06T22:25:01.220

Reputation: 417

1http://codepad.org/45ZgGVk7 - "No errors or program output." And it's quite expected for me. What should've happened? – Qwertiy – 2015-09-06T20:22:05.123