Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
11  
hmmmm.... this one is a brain teaser. +1 –  Tim Seguine Mar 6 at 22:30
5  
@alexwlchan Isn't that the opposite of what we want here? –  arshajii Mar 7 at 2:56
    
@arshajii: yes, of course. *facepalms* My mistake. –  alexwlchan Mar 7 at 3:20
    
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...) –  keshlam Mar 7 at 5:43
7  
I suggest the entire brainfuck language, because BF code just looks like it won't compile. –  snot waffle Mar 10 at 20:21

78 Answers 78

up vote 255 down vote accepted

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.

share|improve this answer
5  
I feel like the first answer just insta-won this right off the bat. –  Aerovistae Mar 7 at 20:34
1  
It's also valid in C99. –  R.. Mar 9 at 21:23
1  
there are warnings with -Wall –  BЈовић Mar 11 at 9:51
2  
@Kiwy It throws warning only for garbage code like above. The -Wall doesn't throw warnings for everything. –  BЈовић Mar 13 at 9:01
6  
Incredible. That is my highest scored answer in the whole SE network by a very large margin! I would never have expected that. –  celtschk Mar 15 at 20:33

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.

share|improve this answer
4  
You got me. I've done both Python and Lua before, and now starting on Ruby. Lua uses that one. –  Riking Mar 7 at 9:07
7  
The meaning of the universe is nothing to see? –  user80551 Mar 12 at 15:47
    

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

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

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.

share|improve this answer
16  
So in other words, it's cheating? –  Mr Lister Mar 7 at 14:33
63  
Cheating is normal in code-challenge competitions. We call it creativity. :P –  Joe Z. Mar 7 at 15:42
26  
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. Mar 7 at 17:11
5  
It's just supposed to make you stop for a second and go 'hey can you do that?' :) –  intx13 Mar 7 at 18:17
8  
@JoeZ. It might look like perl in some cases. –  user80551 Mar 9 at 10:01

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

share|improve this answer
13  
As a lua guy, I was expecting 422 –  mniip Mar 7 at 9:40
2  
Haven't seen this usage before, very neat. –  Nit Mar 9 at 20:33
4  
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 :) –  David Mulder Mar 12 at 0:31
    
What does this output ? And why ? I am curious. –  Nicolas Barbulesco Apr 5 at 8:04
    
@NicolasBarbulesco Give it a try in the browser console and don't forget to read a description in the hidden box. –  VisioN Apr 5 at 10:02

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.

share|improve this answer

Perl

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

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

share|improve this answer
103  
Perl programs generally look like errors. –  ugoren Mar 7 at 17:40
    
@ugoren Only when written and read by those with little knowledge of Perl. –  TLP Mar 11 at 12:11
5  
You gotta love that @ugoren's comment has twice as many upvotes as the answer :) –  tohecz Mar 12 at 23:54
    
Reminds me of the Windows shell trick, "If you're happy and you know it, Syntax Error!" –  Jwosty Jun 22 at 4:41

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.

share|improve this answer
3  
As the question you linked explains, it doesn't run indefinitely, but instead for an extremely long time. –  Kevin Mar 9 at 7:21
    
@Kevin Let's not get unnecessarily pedantic here; "longer than the age of the universe" is, for all practical purposes, "forever". –  arshajii Mar 9 at 17:52
5  
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 Mar 10 at 14:07
    
@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 Mar 10 at 14:22
2  
@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 Mar 10 at 14:27

CoffeeScript

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

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

share|improve this answer

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.

share|improve this answer
    
That's just... wow. –  primo Apr 20 at 2:26

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.

share|improve this answer
    
At Last... Here is the FOO and BAR :) –  VVK Mar 10 at 10:07
1  
That's what foo and bar are for ;) names of things that don't actually matter. –  McKay Mar 10 at 13:49

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

share|improve this answer
7  
This should work in any C-like language that supports // comments. –  Ilmari Karonen Mar 10 at 14:32
    
Yeah, probably, I just wasn't sure while posting –  Piotr Mar 10 at 21:03
9  
Limit one URL per protocol per scope, though. –  Ben Voigt Mar 12 at 17:22
    
You still can use https:// in the same scope. –  Florian F Sep 11 at 20:42

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.

share|improve this answer
6  
your varargs are not varargs ;) –  Navin Mar 8 at 21:04
    
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. –  Nate Kerkhofs Mar 10 at 8:52
12  
I think you should read the original question again: "or produces some other unrelated error." –  Tom Verelst Mar 10 at 8:55

C

main=195;

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

share|improve this answer
    
The opcode for ret is 195, not 193, right? –  Dennis Mar 9 at 12:41
    
Doesn't work for me. I'd expect this to execute the code at address 195. –  nwellnhof Mar 9 at 16:05
    
Tbanks @Dennis, the code was correct, the explanation wrong. –  ugoren Mar 9 at 16:41
2  
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 Mar 10 at 16:29
1  
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. –  handuel Mar 16 at 14:28

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.

share|improve this answer
10  
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. –  hvd Mar 8 at 9:44

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.

share|improve this answer
2  
You should be able to do some tricks with NaN too... –  intx13 Mar 7 at 20:01
7  
meh, this happens in any language with floats. –  Navin Mar 8 at 21:01
3  
@Navin: in any language with floats where division by zero doesn't cause an error. –  nwk Mar 9 at 20:28
    
A.k.a. JavaScript. –  Aerovistae Mar 10 at 14:39
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 Mar 10 at 23:38

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.

share|improve this answer
    
@minitech Actually, if you pass an empty array to UBound it will give you a Subscript out of range error. –  Comintern Mar 7 at 5:30
    
… well. I take that back. VBA =/ –  minitech Mar 7 at 5:32
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 Mar 7 at 5:36

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

share|improve this answer
12  
How did it happen that you posted exactly the same case as I did an hour after me? –  VisioN Mar 7 at 11:21
1  
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 Kashyap Mar 8 at 15:47
1  
Sumeet, don't be sorry. Your answer is nicer — and much clearer — than the answer by @VisioN. –  Nicolas Barbulesco Apr 5 at 8:14

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.

share|improve this answer
11  
Just a bonus: print """""""""Python strings don't have to start with the same number of quotes they end with.""""". –  xfix Mar 9 at 9:54

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.

share|improve this answer
12  
The valid C++ program int main(){(([](){})());} might also look nice when trigraphed... –  Angew Mar 7 at 15:29
1  
What does that one even do? –  Joe Z. Apr 27 at 19:56
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 Aug 1 at 8:34

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

share|improve this answer
8  
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? –  VisioN Mar 7 at 13:05
5  
Yes. Is this cheating? @VisioN –  BeatAlex Mar 7 at 13:53
2  
I'm pretty sure this is cheating. At Least write "HTML" in bold at the top. –  Navin Mar 9 at 1:42
    
Nice ! :-) The trick worked on me. –  Nicolas Barbulesco Apr 5 at 8:17
    
@VisioN — Who did talk of a Web server ? –  Nicolas Barbulesco Apr 5 at 8:18

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

share|improve this answer
3  
This is a popularity contest. No need to cramp up ur code to save bytes. Just reformat it for better readability ;) –  Songo Mar 7 at 3:31
    
I will add a readable version later. I used the same exact answer and didn't edited it at all. –  Ismael Miguel Mar 7 at 10:12
    
foreach(e()as&$e); is the core of this solution. e() is just to keep the syntax-checker going and &$e after the as is what causes the failure. –  TheConstructor Mar 8 at 13:31
    
Actually, everything play an important role. –  Ismael Miguel Mar 8 at 17:32

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.

share|improve this answer
    
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 Mar 8 at 16:02
1  
@Gabe: No, there's no downside other than it being harder to port VBScript code to VB. –  Eric Lippert Mar 8 at 17:51
1  
A name ! Who is this news organisation ? –  Nicolas Barbulesco Apr 5 at 8:26

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.

share|improve this answer

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

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

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.

share|improve this answer
1  
So many frowny faces :( –  Joe Z. Apr 27 at 19:58

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

share|improve this answer
1  
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 Mar 7 at 21:24
1  
@celtschk yes, that was a typo. Thanks for noticing! –  l4mpi Mar 7 at 21:53
    
+1 for stack munging. –  GraphicsResearch Mar 10 at 4:57

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

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.

share|improve this answer

python

 = 3

You expect

SyntaxError: unexpected indent

Instead you get

SyntaxError: invalid character in identifier

Also this:

" " == " "
False

Unicode spaces

share|improve this answer
2  
I just tried this in python 2.7. The output is different from yours. = 3 -> SyntaxError: invalid syntax, " " == " " -> True –  Vader Mar 7 at 1:59
4  
@Vader: NO-BREAK SPACE (U+00A0) will be converted to SPACE (U+0020) on copy/paste under Windows. –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Mar 7 at 2:03
    
@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 Mar 7 at 2:07
    
@Vader: I have no idea about the first one. I only comment about the 2nd one. –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Mar 7 at 2:15
9  
I don't expect SyntaxError: unexpected indent just sayin' –  gcq Mar 7 at 15:13

protected by Timtech May 20 at 22:37

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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