text:
What? No error?
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.

hmmmm.... this one is a brain teaser. +1

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

I suggest the entire brainfuck language, because BF code just looks like it won't compile.

@NigelNquande only if you're not familiar with it... ;)

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.

I feel like the first answer just insta-won this right off the bat.

It's also valid in C99.

there are warnings with -Wall

@BЈовић Wall always throw warning about everything

@Kiwy It throws warning only for garbage code like above. The -Wall doesn't throw warnings for everything.

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.

You got me. I've done both Python and Lua before, and now starting on Ruby. Lua uses that one.

The meaning of the universe is nothing to see?

http://destroyallsoftware.com/talks/wat

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.

So in other words, it's cheating?

Cheating is normal in code-challenge competitions. We call it creativity. :P

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.

It's just supposed to make you stop for a second and go 'hey can you do that?'  :)

@TimS. The point is that it looks like C++ but is actually Haskell. Malbolge won't ever look like anything else.

@JoeZ. It might look like perl in some cases.

It would clash with Control.Monad.

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

This trick can be applied to any languages that accept Unicode token (e.g. Java, C#).

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ , exemplified by your username

too obvious solution

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.

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

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

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

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

@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  ;)

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 — Fonts giving a sense of harmony in displayed text are not broken. They don't need to be fixed.

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

As a lua guy, I was expecting 422

Haven't seen this usage before, very neat.

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

What does this output ? And why ? I am curious.

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

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.

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.

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

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

Perl programs generally look like errors.

@ugoren Only when written and read by those with little knowledge of Perl.

You gotta love that @ugoren's comment has twice as many upvotes as the answer :)

Reminds me of the Windows shell trick, "If you're happy and you know it, Syntax Error!"

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.

As the question you linked explains, it doesn't run indefinitely, but instead for an extremely long time.

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

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.

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

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

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 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 You're clearly an engineer, not a mathematician :)

it would be nice to see an explanation here and not just a "look it up yourself here"

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.

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.

That's just... wow.

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

This should work in any C-like language that supports // comments.

Yeah, probably, I just wasn't sure while posting

Limit one URL per protocol per scope, though.

You still can use https:// in the same scope.

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.

At Last... Here is the FOO and BAR :)

That's what foo and bar are for ;) names of things that don't actually matter.

C
main=195;

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

The opcode for ret is 195, not 193, right?

Doesn't work for me. I'd expect this to execute the code at address 195.

Tbanks @Dennis, the code was correct, the explanation wrong.

@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?

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

@Zack, You're right - on many x86 systems it won't work.

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.

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

@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, 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 In C it's still undefined behavior (and has always been).

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.

your varargs are not varargs ;)

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.

I think you should read the original question again: "or produces some other unrelated error."

Actually, without the \u000d, it would use a reference to the undefined value a.

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.

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.

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.

Just a bonus: print """""""""Python strings don't have to start with the same number of quotes they end with.""""".

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.

You should be able to do some tricks with NaN too...

meh, this happens in any language with floats.

@Navin: in any language with floats where division by zero doesn't cause an error.

A.k.a. JavaScript.

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

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.

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.

The valid C++ program int main(){(([](){})());} might also look nice when trigraphed...

What does that one even do?

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

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.

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

… well. I take that back. VBA =/

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

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

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

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.

Sumeet, don't be sorry. Your answer is nicer — and much clearer — than the answer by @VisioN.

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

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?

Yes. Is this cheating? @VisioN

I'm pretty sure this is cheating. At Least write "HTML" in bold at the top.

Nice ! :-) The trick worked on me.

@VisioN — Who did talk of a Web server ?

Looks like perfectly valid PHP to me.

I edited to make it clear what language this is written in

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.

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: No, there's no downside other than it being harder to port VBScript code to VB.

A name ! Who is this news organisation ?

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

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 ">="?

@celtschk yes, that was a typo. Thanks for noticing!

Is this memory alignment actually specified, or just implemented this way in some compilers?

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.

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.

So many frowny faces :(

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

This is a popularity contest. No need to cramp up ur code to save bytes. Just reformat it for better readability ;)

I will add a readable version later. I used the same exact answer and didn't edited it at all.

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.

Actually, everything play an important role.

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.

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.

Haha, welcome to the site! Kudos for the bravery of this as a first post. :)

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

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

made em more obvious; and spoiler tags are intended cause the tricks arent obvious at first

Ah, much better :)

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?

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

No java programmer would expect an stack overflow in the second snippet. Sorry, that's by far too obvious.

Hate enums :@ Are they electronic or what ???

@VVK codegolfing habit to use enum{ instead of class{saves a byte then

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);
}

its hard to read, but i don't know what kind of error people are expecting from this

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

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

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.

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.

JavaScript
/21 + 21     // SyntaxError in this

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

Could you explain why it works?

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

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.

obviously a syntax error Yeah, obviously!

python
 = 3

You expect
SyntaxError: unexpected indent

Instead you get
SyntaxError: invalid character in identifier

Also this:
" " == " "
False

Unicode spaces

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

@Vader: NO-BREAK SPACE (U+00A0) will be converted to SPACE (U+0020) on copy/paste under Windows.

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳   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: I have no idea about the first one. I only comment about the 2nd one.

I don't expect SyntaxError: unexpected indent just sayin'

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ — The transformation of the non-breaking space into a normal space is due to the Web browser rather than to Windows.

Isn't it supposed to be IndentationError: unexpected indent?

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.

char 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};

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

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

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.

Nice one, although it only works in python2 as python3 changed the rules for comparisons.

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.

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

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.

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 If I do i<=s.size()+1;, I get an index out of bounds (it compiles, but crashes).  Also, if I reference a vector or array this way, it crashes.  With those, I have to use the < operator instead.

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

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.

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.

It didn't work because of characters getting lost.  It is fixed.

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

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

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

Ruby
1 / 0.0

This does not result in a ZeroDivisionError, but in
# => Infinity

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

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

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.

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.

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.

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)]}

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.

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"

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.

:-)

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

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.

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.

"Looks like this should produce an indentation error" - No, it doesn't. At least, not to me.

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?

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

What is an ASI?

@celtschk Automatic Semicolon Insertion

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.

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.

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.

Javascript
a = 1
a+++1

Javascript now has a  triple plus operator

(a++)+1. Outputs a+1 // 0 then adds 1 to a.

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.

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.

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.

String('Test') isn't an String instance , it's just 'Test'. I guess you meant new String('Test')

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.

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

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

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

-1 huh?  no surprises here

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

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 */

What do we learn: don't copy+paste arbitrary data into string literals (or comments, either).

How does this...?

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

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

    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

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

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.

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

Which language is this supposed to be?

@PaŭloEbermann I think JavaScript.

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.

JavaScript
Disturbing string to boolean conversion
booleanValue = Boolean("false");
if(!booleanValue){
    throw "I threw an error!"
}

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;
}

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

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

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

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, but without operator :)

@Qwertiy: Not sure what you are talking about. It's still the trick with comment and label.

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ That is a weird username...

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.

This looks like a bug in the compiler.

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

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

Who can figure it out first?

I guess anyone knowing python knows that there are many modules one doesn't know.

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.

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)

Note to self: read other answers before posting

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

authors: هارون الرشيدى


text:
Do We Sink or Swim?
The Problem
A doomsday scenario is described by three numbers on a single line, n, m, and p. Following that line are n lines with m values per line. Each value represents the total units of water each cell can hold.
The following p lines describe the weather for the next p days. 1 unit of rain falls on a single cell each day. If the amount of water in a cell exceeds the amount it can hold, that cell floods. If multiple adjacent cells are at full capacity, they are treated as one cell that share common neighbors (think Minesweeper when you click on a group of blanks).

A single middle cell has 4 neighbors
Two adjacent, full capacity middle cells are treated as one cell that has 6 neighbors
A single corner cell has 2 neighbors
A single wall cell has 3 neighbors

When a cell floods, a flood event occurs. All excess water is evenly distributed to its neighbors. If that causes one or more neighbors to flood, then another flood event occurs. This continues until the water has settled, or the city has completely flooded.
Example Input

7 5 3
  3 2 3 4 5
  2 2 0 3 4
  1 1 2 3 3
  4 1 2 2 2
  4 1 1 2 2
  4 4 1 2 2
  4 4 2 2 2
  0 0
  1 2
  4 3

0 0 means it rained on row 1, col 1
1 2 means it rained on row 2, col 3 (which can hold zero water and immediately floods!)

After p days of rain, if the city is completely flooded, output Sink. Otherwise, output Swim.
Example Output

Swim

Assumptions

Input may be provided through stdin, read from "city.txt", or accepted as an argument. All three are allowed so as not to invalidate any answers already posted.
Water capacities will be non-negative integers.

40+ teams of undergrad college students (from A&M, UT, LSU, Rice, Baylor, etc.) competing in a programming contest with a variety of languages available could not solve this problem in 5 hours. Because of that, I can't help but mention that there is a catch to this puzzle that makes the solution trivial. Shortest code still wins, because I am that confident that the shortest code will also solve the puzzle.

Is it n lines of m values or the other way around? Your example doesn't match the written specification.

@algorithmshark Corrected

I'm not sure, but it seems to me that you sink if the amount of rain is larger than the sum of rain that all the squares can hold; otherwise you float. Is this it?

@hosch250 Spoiling the fun!

I used to say "I sink, therefore I swim." Unfortunately, I'm now carrying enough fat that I no longer have negative buoyancy.

Yeah, you should have held off mentioning the shortcut. It's definitely facepalm-worthy if you missed it.

"The excess water is evenly distributed to its neighbors." - that is likely to be 1 unit of water. Does it distribute as e.g. 0.25 units to each adjacent cell (assuming a single middle flooded cell)?

OK, got it, that doesn't really matter, does it?

@NeilSlater 0.25 to each neighbor if they aren't already flooded and if it is a middle cell. If one neighbor is flooded, they are treated as one and the water is evenly distributed to ALL neighbors of both cells. For example, two adjacent flooded cells have 6 neighbors. A wall cell would distribute 0.3 repeating to each neighbor, and a corner would distribute 0.5.

@John: Thanks, got it. The trap is trying to run the described process as a simulation as opposed to spotting a key simplifying property of it.

Golfscript, 37 30 characters
New and improved, thanks to PeterTaylor for tips:
~](\(@*\(@@<{+}*>"SwimSink"4/=

Explanation:
Code                     -                                            - Stack
~]                       - parse input into an array of integers      - []
(                        - pop first number and put on stack          - [] 7
\(                       - \ swaps top two, then pop first num again  - 7 [] 5
@                        - bring 3rd down from stack to front         - [] 5 7
*                        - mult. this is grid size                    - [] 35
\(@                      - bring next # out - the days of rain        - [] 3 35
@                        - bring array out                            - 3 35 []
<                        - take first 35 elements out of array.
                           this extracts just the capacities and
                           consumes the rest                          - 3 []
{+}*                     - fold the array using plus - this sums the
                           entire thing                               - 3 86
<                        - greater-than comparison: 3 > 86?           - 0
"SwimSink"4/             - push a string and split it to groups of 4  - 0 ["Swim" "Sink"]

=                        - index into the array using the result of
                           the comparison. if rain > capacity, then
                           sink, else swim                            - "Swim"

Program then terminates, outputting the stack.

Old version + explanation:
[~](\(@*\(@{\(@\-}*\;0>"Sink""Swim"if

Same approach as Fors, just Golfscripted =). Can likely be made more efficient. Input is from stdin.
Explanation:
Code                     -                                            - Stack
[~]                      - parse input into an array of integers      - []
(                        - pop first number and put on stack          - [] 7
\(                       - \ swaps top two, then pop first num again  - 7 [] 5
@                        - bring 3rd down from stack to front         - [] 5 7
*                        - mult. this is grid size                    - [] 35
\(@                      - bring next # out - the days of rain        - [] 3 35
{                        - define a block which...
 \(@                     - brings next number out
 \-                      - swaps and subtracts 2nd down from top
}                                                                     - [] 3 35 {}
*                        - repeat that block 35 times. this ends up
                           pulling the capacities out one by one
                           and decrementing our number-of-days
                           number by each one                         - [] -84
\;                       - swap and kill the array to get rid of
                           unused input                               - -84
0>"Sink""Swim"if         - if the num > 0, evaluate to "Sink",
                           otherwise to "Swim"                        - "Swim"

Program then outputs the stack, which is just the answer.

] without a matching [ will collect the entire stack into an array, so an initial [~] can be simplified to ~]. To get the first grid_size elements of an array, use <, so <{+}* can almost certainly save you a bit on adding the total capacity. 0>"Sink""Swim"if can be 0>"SinkSwim"4/=

@PeterTaylor: Thanks for the tips! Are you sure about ~]? I tried it and it didn't seem to work. The last hack is nice though it has to be "SwimSink" - will use it. and the array thing also seems promising, will get to work on that.

I'm certain: that's a standard trick which I and others have been using for years.

@PeterTaylor: Hmm strange. Try it in the interpreter I linked to - it fails. Then - ok maybe the web interpreter is non-standard. But I tried also with ruby golfscript.rb and it still didn't work... can you verify that it works on your end? I get same error on both: undefined method '+' for nil:NilClass (NoMethodError)

When you insert a string literal to substitute for lack of stdin, you should precede it with a semicolon to remove the empty string which actually comes "from stdin". With that it works fine

@PeterTaylor: Oh awesome! Thanks. Another niche of this neat little language - learned.

C: 100 96 95 characters
n,m;main(p){scanf("%d%d%d",&n,&m,&p);for(n*=m;n--;scanf("%d",&m))p-=m;puts(p>0?"Sink":"Swim");}

Five hours? Took me five minutes. :)
Aragaer, thank you for the simplifications! I did however rearrange the variable declarations and arguments to main, seeing as Clang throws an error if the second argument to main is of any other type than char **.

96 - p;main(n,m){for(scanf("%d%d%d",&n,&m,&p),n*=m;n--;scanf("%d",&m),p-=m);puts(p>0?"Sink":"Swim");}

95 - n,m;main(p){for(scanf("%d%d%d",&n,&m,&p),n*=m;n--;scanf("%d",&m))p-=m;puts(p>0?"Sink":"Swim");}. I've also played with idea of n-=scanf, but not sure if program will be correct after that. First scanf can be moved to the front of for without changing the character count.

n-=scanf... wouldn't work, as n-=1 basically is a pre-increment, so it would miss the south-eastern corner. The other change is great.

Python, 4 lines, 175 characters
import sys
F=sys.stdin
n,m,p=[int(a) for a in F.readline().split()]
print("sink") if p > sum([sum(int(x) for x in F.readline().split()) for a in range(n)]) else print("swim")

Lol, I wonder if the 40+ teams ended up finding the catch... after working it out the hard way.

I was on one of the 40+ teams. We were GIVEN the catch after failing. Everyone in the auditorium facepalmed simultaneously. I think perhaps I shouldn't have mentioned it here. You guys were too quick!

Ouch!  By the way, should I get the input from stdin for these sort of questions? - I'm new to stackexchange. :)

I was going to edit my question to say specify STDIN, but I feared that it would invalidate your answer. I have been reading puzzles here for about a month, and haven't really noticed if people specified STDIN or not.

Edited answer to use stdin - golfed it more anyway! :)

@swalladge Welcome to Codegolf! I recommend making the headline a headline by prepending a #.

You can bring it down to 108 if you use input() and map(): n,_,p=map(int,input().split());print(['sink','swim'][p>sum(sum(map(int,input().split()))for a in range(n))])

Didn't think of map - can get it down to 3 lines, 149 chars with your method but still using stdin: import sys  n,m,p=map(int,sys.stdin.readline().split()) print(["swim","sink"][p>sum([sum(map(int,sys.stdin.readline().split())) for a in range(n)])])

APL,  35
4↑'SwimSink'⌽⍨4×x[3]>+/{+/⎕}¨⍳1⌷x←⎕

Not sure if allowed but it stops accepting input after the "city"
x←⎕ Takes input and store it in variable x (space-delimited numbers are interpreted as a numerical array)
1⌷ Extract index 1 (APL arrays are one-based)
⍳ Generate an array from 1 to the argument (1⌷x←⎕ in this case)
¨ "Map" operation
{+/⎕} Take array from input and return the sum
+/ Sum the array generated by the map operation
4×x[3]> Test if the sum < x[3] (returns 1 or 0), then multiply 4
'SwimSink'⌽⍨ Rotate the string 'SwimSink' by that amount
4↑ Finally, extract the first 4 characters of the string

I think the only part that matters is that it outputs the correct answer for any given input. If this is unusual for CodeGolf, hopefully someone will let me know.

Change ⎕IO←0, then replace 4↑'SwimSink'⌽⍨4× with 'Swim' 'Sink'⊃⍨, x[3] with x[2], and 1⌷x with ⊃x to save two bytes.

@Rainbolt : this entry is 53 bytes long - measuring by utf-8 chars makes this one "appear" more compact when it fact it takes more space than the best entries for J+K above - J is 50 bytes worth of ASCII

@RAREKpopManifesto Why are you telling me this? Did I post a leaderboard somewhere?

@Rainbolt : you're OP right ? so I presumed, apparently inaccurately, that you might have a say regarding the challenge/contest you posted

AWK, 70
n{for(;NF;NF--)s+=$NF;n--}NR==1{n=$1;p=$3}END{print p<s?"Swim":"Sink"}

This is an imrovement by laindir on my submission (86):
NR==1{h=$1;w=$2;r=$3;next}NR<=h{for(i=1;i<=w;++i)c+=$i}END{print(c>r?"Swim":"Sink")}

NR<=h should be NR<=h+1, otherwise you'll get false Sinks as the last line of capacities is skipped. This can also be shortened to 70 as n{for(;NF;NF--)s+=$NF;n--}NR==1{n=$1;p=$3}END{print p<s?"Swim":"Sink"}

@laindir Well, thank you very much for the improvement! I find it so fun, that Awk just comes next to APL, J and K, which were breeded to beat everyone on code-golfing! :-)

@user40989 I don't understand. Awk seem 40-100% longer than J/K/APL, even though they are not golfing languages, but rather (stem from) commercial programming languages.

J (50 char) and K (40) double feature
Turns out, as usual, these two have the exact same structure in their solutions, so they're both here. K is a whole lot shorter, though, which is a pleasant surprise.
>Sink`Swim{~(]<[:+/[+/@".@$+1!:1@#1:)/0 2{".1!:1]1

Explanation:

".1!:1]1 - Read in the first line, and convert to integers.
(...)/0 2{ - Take the items at index 0 and 2 (n and p respectively), and use them as the left and right arguments to the verb (...), respectively.
+1!:1@#1: - Read in n+p lines.
[+/@".@$ - Take ($) the first n rows ([), discarding the rest, and then convert to integers (".) and sum on each row (+/).
]<[:+/ - Add together the row sums, and then compare this value to the right argument, p. We produce true if p is less than the sum.
>Sink`Swim{~ - Select Swim if the above comprasion resulted in true, or Sink if false.

Usage:
   >Sink`Swim{~(]<[:+/[+/@".@$+1!:1@#1:)/0 2{".1!:1]1
7 5 3
3 2 3 4 5
2 0 3 3 4
1 1 2 3 3
4 1 2 2 2
4 1 1 2 2
4 4 1 2 2
4 4 2 2 2
0 0
1 2
4 3
Swim

And now the K:
`Sink`Swim@{z<+//.:'x#0::'(x+z)#`}.. 0:`

Explained:

. 0:` - Read in a line of input, and convert to an array of integers.
{...}. - Use these three numbers n m p as the arguments x y z to this function.
0::'(x+z)#` - Create x+z copies of the input file handle `, and then read in a line for each of them (0::').
.:'x# - Take the first x items, and convert each to a vector of numbers.
z<+// - Sum the entire matrix together, and then test to see if it is greater than z.
`Sink`Swim@ - Return Sink or Swim according to whether the test returned true.

Usage:
  `Sink`Swim@{z<+//.:'x#0::'(x+z)#`}.. 0:`
7 5 3
3 2 3 4 5
2 2 0 3 4
1 1 2 3 3
4 1 2 2 2
4 1 1 2 2
4 4 1 2 2
4 4 2 2 2
0 0
1 2
4 3
`Swim

CoffeeScript - 128 113
A function that takes the string as the only argument:
s=(l)->l=l.split /\n/;[n,m,p]=l[x=0].split /\s/;x+=c|0 for c in r.split /\s/ for r in l[1..n];`p>x?"Sink":"Swim"`

You can remove the indentation, and move everything on first line separated by semicolons. You also write \p>x?"Sink":"Swim"`instead ofif p>x then"Sink"else"Swim"`. Parens for the third statement also aren't needed.

SED, 128
It was fun to write a sed version of this.  It has the following
short-comings:

It assumes the city has more than two columns, to easily recognise
rain lines.
It assumes that the capacity of each city is in the range 0-9.

Here it is:
1d
s/^. .$/R/
G
:a
s/[\n 0]//
/[2-9]/{s/^/C/
y/23456789/12345678/}
s/1/C/
s/0//
s/RC//
h
ta
${s/R//g
s/^Sink//
s/.*C$/Swim/
p}

Call with the -n flag.

SWI-Prolog 79
If you don't mind the fact that this answer takes input by query, rather than via stdin:
s(A,L):-append(A,B),sumlist(B,C),length(L,D),(D>C->E='Sink';E='Swim'),print(E).

The answer doesn't validate input format, but I don't think it is a problem, since programming contest also doesn't require you to do so.
Sample query (using example in the question):
s([[3,2,3,4,5],
   [2,2,0,3,4],
   [1,1,2,3,3],
   [4,1,2,2,2],
   [4,1,1,2,2],
   [4,4,1,2,2],
   [4,4,2,2,2]],
  [(0,0),
   (1,2),
   (4,3)]).

Scala - 128
val a=readLine.split(' ')map(_.toInt);println(if((1 to a(0)map(x=>readLine.split(' ')map(_.toInt)sum)sum)>a(2))"swim"else"sink")

It might be possible to omit some parentheses or something but Scala is really fickle about punctuation and point-free style and () vs {} and whatnot.

Python - 152
import numpy
n, m, p = map(int,raw_input('').split())
print 'swim' if p<numpy.sum(numpy.matrix(';'.join([raw_input('') for i in range(n)]))) else 'sink'

You could start by taking out some whitespace. After ,, before and after ', after )…

Javascript - 73 Characters
for(i=c=0,a=s.split(/\s/);i++<a[0]*a[1];)c+=a[2+i]*1;c>a[2]?"Swim":"Sink"

Assumes the input is in the variable s and outputs Swim or Sink.
Example:
From the original question - entering this into the browser console:
s="7 5 3\n3 2 3 4 5\n2 2 0 3 4\n1 1 2 3 3\n4 1 2 2 2\n4 1 1 2 2\n4 4 1 2 2\n4 4 2 2 2\n0 0\n1 2\n4 3";
for(i=c=0,a=s.split(/\s/);i++<a[0]*a[1];)c+=a[2+i]*1;c>a[2]?"Swim":"Sink"

Outputs:
Swim

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes