972
votes

What is, in your opinion, the most surprising, weird, strange or really "WTF" language feature you have encountered?

Please only one feature per answer.

1
  • 5
    @gablin I think if you combined LISP delimiters with PERL regex using javascript parsing you would cover 90% of the WTF... Sep 19, 2010 at 23:41

320 Answers 320

1
2
3 4 5
11
97
votes

In PHP function names are not case sensitive. This might lead you to think that all identifiers in php are not case sensitive. Guess again. Variables ARE case sensitive. WTF.

function add($a, $b)
{
    return $a + $b;
}

$foo = add(1, 2);
$Foo = Add(3, 4);

echo "foo is $foo"; // outputs foo is 3
echo "Foo is $Foo"; // outputs Foo is 7
6
  • 3
    Classes aren't case-sensitive either.
    – Mauricio
    Jan 23, 2010 at 3:39
  • they should add a compilr option in php.ini to parse case-sensitive !
    – RobertPitt
    Sep 6, 2010 at 18:32
  • @RobertPitt there should not be. Install any badly-written plugin for Drupal, WordPress, etc and you'd be screwed.
    – user142019
    Feb 17, 2011 at 17:29
  • But if the application was specifically home-brew such as Facebook, you would create your own code according to your own standards, this is why I said Option
    – RobertPitt
    Feb 17, 2011 at 17:34
  • 1
    Is there anything in PHP that doesn't cause a "WTF"? Jan 4, 2012 at 3:35
95
votes

I've always been a huge fan of the PHP error thrown when using two colons in a row out of context:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /path/to/file/error.php on line 3

The first time I encountered this I was absolutely befuddled.

2
  • IIRC, that's a double-colon or :: symbol. Weird name though.
    – RCIX
    Jan 6, 2010 at 22:54
  • 8
    The translation is something along the lines of "double dots, twice". Mar 23, 2010 at 1:35
90
votes

In C

a[i++] = i;

It compiles, but it rarely does what you think it ought to do. An optimization change leads to producing wildly different results. And it runs differently on different platforms.

Yet, the compiler's perfectly happy with it.

24
  • 87
    .. but the language is not. More than one reference to something in an expression that is modified in the expression is undefined behaviour.
    – Richard
    Jan 3, 2010 at 15:40
  • 20
    "Why would undefined behavior compile and run?". In general because some things which cause UB in C cannot be detected at compile time, and detecting them at run time (or defining the behaviour) would significantly impact performance. In this particular case, I do think it's a bit feeble that compilers generally don't detect the error. It would certainly end a lot of those arguments. But equally I'm not about to submit a patch to gcc to issue a warning. Presumably your compiler's authors are working on other things, which would get pushed back if the C language mandated an error for this code. Jan 3, 2010 at 17:34
  • 13
    @cschol: "Compilers (or their manufacturers) generally assume you are aware" That's precisely the WTF of C.
    – S.Lott
    Jan 3, 2010 at 17:41
  • 29
    It's an inevitable consequence of the fact that C permits low-level programming, but CPUs do different things in response to low-level errors. If C had defined all behaviours, then C on x86 would be slow, because it would be attempting to emulate edge-cases from a PDP-7. If you don't like it, you either write in assembly for a particular architecture with fully defined behaviour, or you don't write low-level code. Seems a bit weird though to say in effect, "C's wtf is that it's a portable low-level language". That should not be surprising, since that is its purpose. Jan 3, 2010 at 17:56
  • 20
    with the the -Wall flag, gcc warns about this warning: operation on 'i' may be undefined
    – Hasturkun
    Jan 5, 2010 at 11:24
80
votes

Python 2.x

>>>True = False
>>>True
False

You can really make someone become crazy with this one.

5
  • 9
    You can't do this in Python 3.x anymore. It gives a syntax error.
    – Reshure
    Jan 7, 2010 at 17:52
  • 3
    Hmm. I think this might be the answer to questions like "Why should I use Python 3?" (eg stackoverflow.com/questions/1921742/…)
    – Ewan Todd
    Jan 9, 2010 at 20:12
  • 7
    That's messed up, and hilarious. For twice the fun, True,False = False,True. What makes it doubly awful is that 1==1 afterwards still returns True. It wouldn't be such a big deal if True and False were simply consistent (global) labels
    – kibibu
    Mar 23, 2010 at 3:43
  • In C: #define true false but only if stdbool.h is used.
    – user142019
    Feb 17, 2011 at 17:33
  • This is one more reason to never use do if test() == True:, but just do if test():, which is suggested in Python (same of course for if not test(): instead of if test() == False:) Sep 13, 2011 at 17:11
72
votes

Oracle has a couple of SQL WTF issues.

  1. Oracle's treatment of empty strings as null.

  2. Treatment of null values in a "<>" comparison.

    create table wtf (key number primary key, animal varchar2(10));    
    insert into wtf values (1,'dog');
    insert into wtf values (2,'');
    insert into wtf values (3,'cat');    
    select * from wtf where animal <> 'cat';
    

The only row returned is the (1,'dog') row.

21
  • 6
    I wish SQL Server treated empty strings as NULLs. After all, what is a practical difference between the two? My DB is full of CHECK (Name <> ''). Jan 4, 2010 at 12:24
  • 109
    The practical difference between the two is that '' is a value. NULL is not.
    – recursive
    Jan 4, 2010 at 20:13
  • 6
    Andrey Shchekin: What is the meaning of the life? Jan 5, 2010 at 0:16
  • 6
    A value is a known quantity, amount, or measured value, numeric or otherwise. For example a "special instructions" field could be '' if there are no special instructions, and NULL if that field has not yet been filled.
    – recursive
    Jan 5, 2010 at 0:17
  • 64
    The string '' should no more be treated as NULL than should the integer 0.
    – Ben Blank
    Jan 5, 2010 at 0:31
70
votes

Java has a whole freakin book about them.

book http://www.javapuzzlers.com/lg-puzzlers-cropped.jpg

Java Puzzlers

1
70
votes

In JavaScript, void is not a keyword, it is not a type declaration, nor is it a variable name, and it is also not a function, nor is it an object. void is a prefix operator, similar to -, --, ++, and !. You can prefix it to any expression, and that expression will evaluate to undefined.

It is frequently used in bookmarklets, and inline event handlers, as in this somewhat frequent example:

<a href="javascript:void(0)">do nothing</a>

The way it's used in that example makes it look like a function invocation, when really it's just an overly clever way of getting the primitive undefined value. Most people don't really understand the true nature of void in JavaScript, and that can lead to a lot of nasty bugs and weird unexpected things happening.

Unfortunately, I think the void operator is the only truly guaranteed way to get the undefined value in JavaScript, since undefined, as pointed out in another answer, is a variable name that can be reassigned, and {}.a can be messed up by Object.prototype.a = 'foo'

Update: I thought of another way to generate undefined:

(function(){}())

Eh, a bit verbose though, and it's even less clear that returning "undefined" is its purpose.

14
  • 1
    I usually create normal divs/spans with an onclick event and a css style of cursor:pointer (or something like that)
    – hasen
    Jan 20, 2010 at 3:50
  • 2
    I just use href="#somemeaningfulfragmentid", and when I assign a click handler I get it to return false. I can often encode some useful things in the fragment id that I can retrieve in the click handler. Then if javascript is disabled, the link can still do something useful if there's an element with a cooresponding id- The browser can scroll to it. Alternatively, the link points to a regular page that reproduces as best as possible the javascript functionality.
    – Breton
    Jan 20, 2010 at 4:34
  • I thought it was normally done like this: (function(){})(), with the parentheses in different places
    – Eric
    May 20, 2010 at 12:28
  • 3
    @hasen j: add tabindex=0 to those elements, otherwise they won't be keyboard-accessible.
    – Kornel
    Jul 21, 2010 at 12:34
  • 3
    Why not just use a variable, like this? var foo; Variables are assigned the default value of undefined, regardless of what the variable "undefined" is. The same goes for function arguments, as already noted.
    – Pauan
    Oct 25, 2010 at 12:15
69
votes

Perl has the yada yada operator (...).

The so called “yada yada” operator of Perl 6 heritage is a shortcut to mark unimplemented code:

if ($condition) { ... }

is the same as

if ($condition) { die "not yet implemented" }
3
  • 1
    Incredibly helpful though. IE: try finding unimplemented code? ack '\.{3}' Aug 15, 2010 at 14:27
  • 5
    ack "not yet implemented" is more maintainable.
    – berkus
    Nov 18, 2010 at 14:13
  • @Berkus, not if someone says "This hasn't been made" one time, but "not yet implemented" another. Jan 7, 2012 at 21:01
68
votes

In fortran (77 for sure, maybe in 95 as well), undeclared variables and arguments beginning with I through N (the "in" group) will be INTEGER, and all other undeclared variables and arguments will be REAL (source). This, combined with "whitespace optional in certain cases" resulted in one of the most famous bugs.

As told by Fred Webb in alt.folklore.computers in 1990:

I worked at Nasa during the summer of 1963. The group I was working in was doing preliminary work on the Mission Control Center computer systems and programs. My office mate had the job of testing out an orbit computation program which had been used during the Mercury flights. Running some test data with known answers through it, he was getting answers that were close, but not accurate enough. So, he started looking for numerical problems in the algorithm, checking to make sure his tests data was really correct, etc.

After a couple of weeks with no results, he came across a DO statement, in the form:

DO 10 I=1.10

This statement was interpreted by the compiler (correctly) as:

DO10I = 1.10

The programmer had clearly intended:

DO 10 I = 1, 10

After changing the . to a , the program results were correct to the desired accuracy. Apparently, the program's answers had been "good enough" for the sub-orbital Mercury flights, so no one suspected a bug until they tried to get greater accuracy, in anticipation of later orbital and moon flights. As far as I know, this particular bug was never blamed for any actual failure of a space flight, but the other details here seem close enough that I'm sure this incident is the source of the DO story.

I think it's a big WTF if DO 10 I is taken as DO10I, and that in turn, because of implicit declarations is taken to be of type REAL. And it's a great story.

11
  • 7
    F90+ has this "feature" as well, but you can suppress it with the IMPLICIT NONE statement. Also, the implicit typing applies to function names as well; I spent a particularly unpleasant evening trying to figure out why an INTEGRATE function I had written for a numerical methods course would always return 0.
    – Pillsy
    Jan 5, 2010 at 14:39
  • implicit none is backported to a number of fortran 77 compilers too. Jan 8, 2010 at 4:29
  • 1
    This made me shudder -- the ability to rename alphanumeric variable names without changing program semantics is just so ingrained in me. This makes about as much sense to me as having undeclared variables be INTEGER or not depending on whether the current line number is divisible by 7. Jan 31, 2010 at 5:47
  • 3
    Fortran ignores all whitespace! DO10I=1.10 and D O 1 0 I = 1 . 1 0 are treated the same! May 2, 2010 at 16:28
  • 1
    I think you and the compiler better agree on what the code should do when you're dealing with (expensive) space missions :-) Aug 14, 2010 at 7:20
63
votes

My favorite little C++ syntax trick is that you can put URL's (with some restrictions) directly into the code:

int main( int argc, char *argv[] )
{
    int i=10;

    http://www.stackoverflow.com
    return 1;
}

This compiles just fine.

Syntax highlighting kind of spoils the joke, but it's still fun.

3
  • very nice, but how is "http:" compiled?
    – Serg
    Nov 13, 2011 at 20:08
  • 3
    @Serg: http: is a GOTO label, it defines a position in the current scope you can jump to by calling goto http;.
    – user244343
    Dec 7, 2011 at 0:59
  • 1
    Then later you can write goto http;//www.stackoverflow.com Dec 16, 2011 at 4:13
58
votes

I would not dare to claim that XML is a programming language, but isn't it close to our heart? :-)

The strangest feature, to my mind, in XML is that the following is a well-formed document:

<_....>
</_....>

Here is the the lexical definition of NT-Name that allows consecutive dots.

9
  • 95
    If I read the spec right, I could also have <:-D>..</:-D> as tag. Great, I'm going to abuse this immediately!
    – Esko
    Jan 4, 2010 at 8:23
  • 7
    Esko: that won't quite work, because the namespaces spec prevents you from having a colon with no prefix before it :) You will have to put at least one valid start character before the colon. XML does not need the navigation programming languages like Java do (e.g. foo.bar); why they did not restrict the lexical definition further, I don't know. Laziness? Or they just did not care.
    – xcut
    Jan 4, 2010 at 9:49
  • 15
    So by giving a hat (C) to the smiley face it should be valid? <o_o>OMG</o_o> is directly valid tho'
    – Esko
    Jan 4, 2010 at 14:54
  • 1
    @Talvi, as @xcut pointed out, the namespaces spec prevents you from having a colon with no prefix before it (but parsers must accept those colons anyway). Also, the 3rd < (which I assume is supposed to be text content) is illegal. How about <_><_·.>:/:>_.·</_·.></_>
    – LarsH
    Dec 1, 2010 at 22:04
  • 3
    If you don't keep XML far away from your heart, it will cut you and you will bleed. Death of a thousand angle brackets. Dec 15, 2010 at 14:19
57
votes

Inheriting from random class in Ruby:

class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].sample
   ...
end

(first seen at Hidden features of Ruby)

3
  • 11
    It seem more like a side effect of language design, nice example by the way Jan 10, 2010 at 14:59
  • 7
    Possible in Python too: class C ( random.choice([A, B]) ): ;-) Jan 12, 2010 at 6:46
  • 2
    Probably possible in most dynamic languages. For eg in Perl: package C; use base (qw/A B/)[ int(rand(2)) ];
    – draegtun
    Aug 14, 2010 at 19:22
55
votes

I was taken by surprise that you can change a class's inheritance chain in Perl by modifying its @ISA array.

package Employee;
our @ISA = qw(Person);
# somwhere far far away in a package long ago
@Employee::ISA = qw(Shape); 
# Now all Employee objects no longer inherit from 'Person' but from 'Shape'
6
  • 5
    Argh. That's true? Really weird!! :) Jan 4, 2010 at 14:34
  • 3
    This is also possible in Objective-C too, if I remember correctly. I think KVO in Cocoa/GNUstep works by dynamically subclassing the observed object at runtime to intercept accessor methods. The object's isa / class_pointer is changed to the newly created subclass.
    – dreamlax
    Jan 4, 2010 at 20:38
  • 6
    @David: yeah, that's because most languages don't have object-oriented aspects grafted on to the language as an afterthought. Jan 6, 2010 at 14:00
  • 7
    It's called meta-programming. Being able to change classes (by adding parents, methods, etc) as part of the program. Very useful for things like debugging (like adding a Logger parent class to any existing class) and extending.
    – mpeters
    Jan 7, 2010 at 17:06
  • 8
    I'm failing to see what's weird -- it's merely a dynamic language doing what it was told to do. And it enables lots of useful things like Class::MOP.
    – hobbs
    Jan 9, 2010 at 1:53
54
votes

I love the fact that this sort of thing is fine in JavaScript:

var futureDate = new Date(2010,77,154);
alert(futureDate);

and results in a date 77 months and 154 days from the 0th day of 0th month of 2010 i.e. Nov 1st 2016

3
  • 13
    Oh my gosh, that's horrible. Before the computer calculates the date for me, I have to calculate the date for it! Jan 4, 2010 at 21:04
  • 15
    And something's supposed to be wrong here? It's just auto-normalizing dates. While it doesn't really make much sense used this way when the numbers are the result of math it can be useful. Jan 5, 2010 at 4:32
  • 3
    one program that I once worked on had this "feature" on the timestamp class, but only for hours/minutes/seconds. Days/months/years were confined to their normal ranges. It caused me a lot of grief when people would enter times like "25:70:99" and it would convert them into something on the next day instead of throwing an error like I expected. I agree that this feature can be useful, but it should be opt-in.
    – rmeador
    Jan 6, 2010 at 17:53
45
votes

In JavaScript, undefined is a global variable whose default value is the primitive value undefined. You can change the value of undefined:

var a = {};
a.b === undefined; // true because property b is not set
undefined = 42;
a.b === undefined; // false

Due to the mutability of undefined, it is generally a better idea to check for undefined-ness through typeof:

var a = {};
typeof a.b == "undefined"; // always true
5
  • omfg. how did I not know about this? the wheels in my head that think evil obfuscation thoughts are spinning very fast right now...
    – rmeador
    Jan 6, 2010 at 20:47
  • void(0) is a more reliable way of getting the undefined value. However, read my answer to see why this is a bad idea as well. (in short, void(0) isn't doing what it looks like it's doing).
    – Breton
    Jan 6, 2010 at 23:26
  • 23
    "undefined" is not a reserved words. It's a variable name, which happens to be undefined. Being undefined is a type, shown by typeof.
    – niXar
    Jan 7, 2010 at 14:07
  • 4
    This also goes for Infinity and NaN. This will be changed in Firefox 3.7, by the way: whereswalden.com/2010/01/12/… Feb 7, 2010 at 19:56
  • 2
    That's why most libraries define their local scope like (function (undefined) { ... })();. This way you have a guaranteed undefined value in your scope (since omitted parameters are undefined always). And it's compressed better than typeof checks. Feb 5, 2011 at 16:59
45
votes

In ruby/python/c, you can concatenate strings just like this:

a = "foo" "bar"
print a # => "foobar"
11
  • 82
    THat's not WTF --- that's awesomeness Jan 3, 2010 at 15:36
  • 12
    @redder: as long as they're constant strings - yes.
    – Asaf R
    Jan 3, 2010 at 16:50
  • 18
    Oh yeah. That's fun if you have a variadic function in C and forget the comma between two symbolic constants. All params offset by one, and crashes galore. But is nice in e.g. ObjC, where you can use @"" FILE to get an NSString with the file name.
    – uliwitness
    Jan 3, 2010 at 18:22
  • 3
    As a side note in Obj-C, when you use it with NSString constants (@""), you don't need any extra @s. For example, @"foo" "bar". This can be really useful for breaking strings across lines...
    – jtbandes
    Jan 5, 2010 at 2:46
  • 6
    In Python this is not "string concatenation" - it is part of the parsing of the code. it is one ot the few thigns taht happen at parse ("compile") time, instead of runtime. So, print "a" + "b" and print "a" "b" Yield the same result, but are fundamentally different things - the later should only be used for splitting large string constants over multiple lines of code, (where you can't afford the triple quote - """ bla """ style due to the \n's, that is)
    – jsbueno
    Jan 6, 2010 at 18:18
43
votes

In Forth, anything that does not contains spaces can be an identifier (things that contain spaces take a bit of work). The parser first checks if the thing is defined, in which case it is called a word, and, if not, checks if it is a number. There are no keywords.

At any rate, this means that one can redefine a number to mean something else:

: 0 1 ;

Which creates the word 0, composed of 1, whatever that was at the time this was executed. In turn, it can result in the following:

0 0 + .
2 Ok

On the other hand, a definition can take over the parser itself -- something which is done by the comment words. That means a Forth program can actually become a program in a completely different language midway. And, in fact, that's the recommended way of programming in Forth: first you write the language you want to solve the problem in, then you solve the problem.

3
  • 2
    Wow. That's pretty crazy. Is it useful? or is it just a pain? Jan 5, 2010 at 0:51
  • 4
    Well, I never encountered any programs redefining numbers themselves -- just because it is possible doesn't mean it is a good idea, after all. There are words starting with numbers, though, such as 0BRANCH. As for taking over the parser, that's pretty common, as the language is pretty much geared towards building DSLs. Jan 5, 2010 at 16:07
  • 2
    I was trying to think back to the mid-80s when I used Forth. You nailed it with the definition taking over the language. Since it was right around the place and time of the Homebrew Computer Club, there were some real characters messing around with Forth and the kit computers like the Z80 S100-bus. Later Forth was an alternative to 6502 assember on Atari 2600 and Commodore 64 -- darn kids nowadays have NO IDEA that TOTAL ADDRESSABLE RAM was 64k. That's it!
    – reechard
    Jan 10, 2010 at 8:07
43
votes

I added the "format" function to Lisp in about 1977, before "printf" even existed (I was copying from the same source as Unix did: Multics). It started off innocently enough, but got laden with feature after feature. Things got out of hand when Guy Steele put in iteration and associated features, which were accepted into the Common Lisp X3J13 ANSI standard. The following example can be found at Table 22-8 in section 22.3.3 of Common Lisp the Language, 2nd Edition:

(defun print-xapping (xapping stream depth)
  (declare (ignore depth))
  (format stream
      "~:[{~;[~]~:{~S~:[->~S~;~*~]~:^ ~}~:[~; ~]~ ~{~S->~^ ~}~:[~; ~]~[~*~;->~S~;->~*~]~:[}~;]~]"
      (xectorp xapping)
      (do ((vp (xectorp xapping))
           (sp (finite-part-is-xetp xapping))
           (d (xapping-domain xapping) (cdr d))
           (r (xapping-range xapping) (cdr r))
           (z '() (cons (list (if vp (car r) (car d)) (or vp sp) (car r)) z)))
          ((null d) (reverse z)))
      (and (xapping-domain xapping)
           (or (xapping-exceptions xapping)
           (xapping-infinite xapping)))
      (xapping-exceptions xapping)
      (and (xapping-exceptions xapping)
           (xapping-infinite xapping))
      (ecase (xapping-infinite xapping)
        ((nil) 0)
        (:constant 1)
        (:universal 2))
      (xapping-default xapping)
      (xectorp xapping)))
2
  • 19
    +1 for a guy who was there. This answer is refreshing considering the plethora of off-the-cuff answers where somebody is surprised C# doesn't work like C++, etc.
    – John K
    Aug 30, 2010 at 3:02
  • 1
    @Biosci3c -- It made me a little surprised and pleased that I hadn't seen any Lisp entries yet. Perhaps that means it does not have much unexpected behavior.
    – Mark C
    Dec 15, 2011 at 17:42
42
votes

MUMPS. There are lots of WTF features, I've picked one, the if statement. (Note that I'm using a rather verbose coding style below in order to accomodate those who don't know the language; real MUMPS code is usually more inscrutable to the uninitiated.)

if x>10 do myTag(x)    ; in MUMPS "tag" means procedure/function
else  do otherTag(x)

This is similar to saying in Java:

if (x > 10) {
  myMethod(x);
} else {
  otherMethod(x);
}

Except that in MUMPS, the else statement isn't syntactically part of the if block, it is a separate statement that works by examining the built-in variable $TEST. Every time you execute an if statement it sets $TEST to the result of the if statement. The else statement actually means "execute the rest of line if $TEST is false, otherwise skip to the next line".

This means that if x was greater than 10 and thus the first line called myTag, and myTag contains if statements, then the behavior of the else depends not on the if in the line above it but on the last if evaluated inside of myTag! Because of this "feature", MUMPS coders are generally taught write the above code like this to be safe:

if x>10 do myTag(x) if 1
else  do otherTag(x)

The if 1 at the end of the first line ensures that $TEST is set correctly before control proceeds to the next line. (BTW, the spacing here has to be just so, with two spaces after the else and one space in all the other places. The spacing is odd but at least it's very orthogonal once you understand the pattern.)

3
  • 28
    This is the most staggeringly bad piece of language design I have seen yet. My heart goes out to you and your fellow MUMPS programmers. Jan 31, 2010 at 7:46
  • At least the irritation of those quirks is moderate somewhat by the small size of the language. TBH what really gets me is that MUMPS has a very powerful type abstraction -- efficient sorted n-ary trees -- but they are not first-class objects. There is no other aggregate data type. The language lacks reference or pointer types so you can't, e.g., build a tree from the bottom up. This makes some algorithms very awkward to implement.
    – Nate C-K
    Feb 4, 2010 at 21:30
  • 1
    That's absurd! Absurd I tell you! Apr 23, 2010 at 21:29
41
votes

Tri-valued logic of nulls in ANSI SQL.

5
  • 101
    I neither agree nor disagree with this
    – cindi
    Jan 7, 2010 at 11:49
  • 6
    I know someone made a comment but it doesn't show up in the query results.
    – sal
    Jan 7, 2010 at 21:27
  • I actually like this 3-valued logic, though it may bite the innocent.
    – user192472
    Jan 8, 2010 at 10:34
  • 6
    Given that SQL has NULLs, 3-VL seems a better idea than failing the statement or making up some incorrect rules. Jan 8, 2010 at 18:17
  • NULL means simply you don't know if something is true or false. It's logical. Jan 3, 2011 at 10:36
41
votes

An amusing side effect of Python's everything-is-really-a-reference:

>>> a = [[1]] * 7
>>> a
[[1], [1], [1], [1], [1], [1], [1]]
>>> a[0][0] = 2
>>> a
[[2], [2], [2], [2], [2], [2], [2]]
6
  • 8
    you asked for 7times the same object not 7 times for a copy. I think this is normal, not WTF
    – Kugel
    Jan 7, 2010 at 3:04
  • 8
    normal yes, but I know I've been bitten by this one a few times
    – cobbal
    Jan 7, 2010 at 9:07
  • 5
    Not coming from a Python background, that really threw me off. +1
    – Maulrus
    Jun 9, 2010 at 3:54
  • 1
    Try def x(y, z=[]): z.append(y); print z
    – cthom06
    Sep 10, 2010 at 14:33
  • 1
    No, believe me, as someone who uses Python all the time, this couldn't be more expected. By the way, your example doesn't work. Try [list() for i in range(7)]. Mar 16, 2011 at 18:08
41
votes

In JavaScript, you can use a double bitwise negation (~~n) as a replacement for Math.floor(n) (if n is a positive number) or parseInt(n, 10) (even if n is negative). n|n and n&n always yield the same results as ~~n.

var n = Math.PI;
n; // 3.141592653589793
Math.floor(n); // 3
parseInt(n, 10); // 3
~~n; // 3
n|n; // 3
n&n; // 3

// ~~n works as a replacement for parseInt() with negative numbers…
~~(-n); // -3
(-n)|(-n); // -3
(-n)&(-n); // -3
parseInt(-n, 10); // -3
// …although it doesn’t replace Math.floor() for negative numbers
Math.floor(-n); // -4

A single bitwise negation (~) calculates -(parseInt(n, 10) + 1), so two bitwise negations will return -(-(parseInt(n, 10) + 1) + 1).

Update: Here’s a jsPerf test case comparing the performance of these alternatives.

4
  • This is very interesting! Also note that, for some reason, function parseInt(x, 10) is about 3 times slower than Math.floor().
    – Harmen
    Jul 2, 2010 at 15:42
  • 3
    Bitwise operators will truncate their inputs to signed 32 bit values. Math.floor(4294967295.1) == 4294967295; parseInt("4294967295.1") == 4294967295; (4294967295.1 | 4294967295.1) == -1;
    – rpetrich
    Aug 15, 2010 at 0:16
  • That’s right, @rpetrich. I should’ve mentioned that. I updated the answer with a link to the performance test case on jsPerf. Aug 15, 2010 at 7:46
  • How does something like this even get discovered? Sep 11, 2010 at 22:42
39
votes

Not so much a weird feature, but one that's really irritating from a type-safety point of view: array covariance in C#.

class Foo { }
class Bar : Foo { }
class Baz : Foo { }

Foo[] foo = new Bar[1];
foo[0] = new Baz(); // Oh snap!

This was inherited (pun intentional) from Java, I believe.

13
  • 26
    The point isn't that it should prevent me from adding new Baz() to foo; rather, it shouldn't have let me coerce the array into type Foo[] in the first place. An array of Foo makes two guarantees: 1) that any element retrieved from it will have type Foo, and 2) that any object of type Foo may be assigned to the array. This obviously isn't the case if the underlying type of the array is actually Bar. Jan 4, 2010 at 0:13
  • 11
    Eric Lippert wrote a good series of articles on type variance, the second of which illustrates the problems with array covariance: blogs.msdn.com/ericlippert/archive/2007/10/17/… Jan 4, 2010 at 0:18
  • 7
    In Programming Scala, this behaviour is talked about on page 391: "When asked [why Java has covariant arrays], James Gosling, the principal inventor [of Java], answered that they wanted to have a simple means to treat arrays generically. For instance, they wanted to be able to write a method to sort all elements of an array, using a signature like the following that takes an array of Object: void sort(Object[] a, Comparator cmp) { ... }. Covariance of arrays was needed so that arrays of arbitrary reference types could be passed to this sort method."
    – cdmckay
    Jan 4, 2010 at 7:41
  • 8
    @Kobi: I don't follow. Bar[] is not a subtype of Foo[], so what do inheritance and polymorphism have to do with it? The reason that this kind of type variance shouldn't be allowed is that an array allows both read and write operations on its underlying type. A read-only type may be type covariant, while a write-only type may be type contravariant, but a read/write type may not be type variant at all. Jan 4, 2010 at 10:58
  • 4
    No, Java does not have templates. Templates generate new code for every type that uses the template. C++ templates do this, Java generics do not. Java generics are more similar to C# generics; the difference is that C# retains information about type parameters in the bytecode whereas Java discards this information after using it for type-checking at compile time.
    – Nate C-K
    Jan 7, 2010 at 17:52
39
votes

My favorite weirdness in C is 5["Hello World"], but since that was already posted, my next-favorite weirdness is the Windows versioned-structure initialization hack:

void someWindowsFunction() {
    BITMAPINFOHEADER header = {sizeof header};

    /* do stuff with header */
}

That one, subtle line accomplishes the following:

  1. Declares a BITMAPINFOHEADER structure
  2. Concisely sets the "size" member of the structure, without hardcoding a size constant (since many Window structures, including BITMAPINFOHEADER, follow the convention of specifying the size of the structure as the first member}
  3. Declares the version of the structure (since many Windows structures, including BITMAPINFOHEADER, identify their version by the declared size, following the convention that structures definitions are append-only)
  4. Clears all other members of the structure (a C standard behavior when a structure is incompletely initialized).
2
  • 13
    Actually, I find this to be an elegant solution, not a WTF at all. Jan 5, 2010 at 14:59
  • 6
    At what point did I say it was a WTF? The original question asked for "surprising, weird, strange or really 'WTF'". The surprising thing to me was how expressive one line can be when it combines a little-used but well-defined language behavior with a simple coding convention.
    – Tim Lesher
    Jan 5, 2010 at 23:01
38
votes

Java; making all object instances be mutexes.

7
  • Well, to be fair, the synchronized statement would be a lot harder to use if that wasn't the case. Jan 5, 2010 at 1:03
  • 6
    What is the problem with shipping a mutex class with the JVM that could then be used in every synchronized statement? What would be more difficult then?
    – codymanix
    Jan 5, 2010 at 1:35
  • 5
    Maybe he hates multi core/cpu systems.
    – mP.
    Jan 5, 2010 at 4:35
  • 11
    Uh, maybe he hates adding overhead to every single object you allocate, or is observing that if you're locking on a per object basis you're almost certainly doing it wrong, or that it could've been accomplished with a generics library instead of burdening the core language syntax or ... Jan 7, 2010 at 15:44
  • 3
    Since 1.5 there has been a dedicated class: java.util.concurrent.locks.ReentrantLock but it could have been a separate class from the beginning. Most objects don't need built-in locks, especially immutable objects.
    – finnw
    Feb 1, 2010 at 5:20
37
votes

In PHP one can do:

System.out.print("hello");
5
  • WTF?! Is this documented anywhere?
    – PureForm
    Nov 8, 2010 at 22:02
  • 4
    Didn't want to believe it. But is actually works, ask e.g. codepad.org. jansch.nl/2007/03/09/systemoutprint-in-php explains why it works, but it's still weird (TRWTF is how PHP swallows references to undefined variables and treats UndefinedConstant as "UndefinedConstant")
    – user395760
    Nov 8, 2010 at 22:13
  • holly s**t. this is a real WTF
    – gion_13
    Nov 22, 2011 at 8:26
  • I don't understand what's so weird about this. Could you explain what it's actually doing? Dec 6, 2011 at 21:05
  • @NickRetallack String coercion is what PHP does... well, not best, but everywhere and with vigor. Unknown constants? Make 'em strings! What you end up with is the same as if you said "System" . "Out" . print("hello");, which concatenates those strings with the output of print (whatever it is), and then does nothing with it. Meanwhile, the "print" function sends whatever you passed it to the output.
    – Adam Bard
    Dec 15, 2011 at 23:04
36
votes

In JavaScript:

alert(111111111111111111111) // alerts 111111111111111110000

This was quite damaging to some 64bit keys I passed back and forth in JSON.

2
  • Yes, I think so, if you add some more 1111 it would be more obvious. Jan 7, 2010 at 11:33
  • 10
    All numbers in ECMAscript are Nubmbers which is an IEEE float.
    – LiraNuna
    Jan 7, 2010 at 19:28
35
votes

else in Python's for loops.

From the Python documentation:

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print n, 'equals', x, '*', n/x
            break
    else:
        # loop fell through without finding a factor
        print n, 'is a prime number'

Output:

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
5
  • 3
    @Daniel: I believe the else is only executed if the for loop does not exit because of a break statement. Sep 11, 2010 at 13:05
  • 1
    a quick example code snippet would be nice here for those not familiar with python
    – scunliffe
    Sep 11, 2010 at 13:56
  • There's an else for while and try too.
    – Plumenator
    Sep 13, 2010 at 6:08
  • 3
    try: else: works just like you would expect (gets executed when no exception is raised); for/white: else: doesn't match the intuition of ~50% of programmers. I expected it to be executed only if the main body of the for/while loop was never executed, but that's not the case -- the else clause is executed only if no break statement inside the for/while loop is executed. Confused yet? Sep 25, 2010 at 1:36
  • 1
    This is used if there are two ways of exiting a loop. Say you are searching a list. You exit the loop when you find what you want, or you hit the end of the list without finding it. In other languages, I set flags "itemFound = False" and test the value of the flag after the loop. The else is kind of like the post loop test, but you don't need a flag. Only thing is, if there are three or more ways to exit the loop (e.g. found, not found, too many occurrences, bad items), you still need flags. So I tried using for-else once, then dropped it. Dec 16, 2011 at 2:22
33
votes

Some early dynamic languages (including, if I remember correctly, early versions of Perl) hadn't figured out what was good dynamism and what was bad dynamism. So some of them allowed this:

1 = 2;

After that statement, the following would be true:

if(1 + 1 == 4)
3
  • 14
    or perhaps: 2 = 2.5; then if(2 + 2 == 5)
    – GameFreak
    Feb 7, 2010 at 19:41
  • 2
    What would 2=1; 5=2; 5+2=? Is it 3? Or 2?
    – Yahel
    Oct 23, 2010 at 20:39
  • @yahelc that'd be 2. This issue crops up in languages that just assume any lvalue is a valid identifier, and will allow you to shadow literals like 1 with variables of the same name. Rename 2 and 5 to x and y and you'll see what this looks like. x=1; y=x; x+y -> 2. Dec 6, 2011 at 21:01
30
votes

In Python, the "compile time" (or declaration time) evaluation of function arguments can be confusing:

def append(v, l = []):
    l.append(v)
    return l


print append(1)
print append(2)

>>> [1]
>>> [1,2]

The intention might have been:

def append(v, l = None):
    if l is None:
        l = []
    l.append(v)
    return l

print append(1)
print append(2)

>>> [1]
>>> [2]

This behavior is useful for things like caching, but it can be dangerous.

A bonus feature: tuples with mutable contents:

a = (1,2,[3])
a[2][:] = [4] # OK
a[2] = [2] # crashes
4
  • 1
    To be a major WTF it'd have to be something that commonly causes problems.
    – Roger Pate
    Jan 5, 2010 at 12:35
  • 5
    @Roger Pate: Every single Python programmer gets bitten by this at some point, after which they have to constantly keep it in the back of their mind. That is exactly what constitutes a language-gotcha ( ferg.org/projects/python_gotchas.html#contents_item_6 ). Jan 6, 2010 at 3:21
  • 2
    You can't return l.append(1). You have to l.append(1); return l because list.append returns nothing.
    – Chris Lutz
    Jan 6, 2010 at 5:45
  • fwiw, you can't hash a. Every element of a tuple has to be hashable in order for you to hash it. I mention this because hashability is the main reason for immutable types like tuples.
    – asmeurer
    Jan 14, 2011 at 4:53
1
2
3 4 5
11

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