What is, in your opinion, the most surprising, weird, strange or really "WTF" language feature you have encountered?
Please only one feature per answer.
What is, in your opinion, the most surprising, weird, strange or really "WTF" language feature you have encountered?
Please only one feature per answer.
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
Option
Feb 17, 2011 at 17:34
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.
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.
-Wall
flag, gcc warns about this warning: operation on 'i' may be undefined
Jan 5, 2010 at 11:24
Python 2.x
>>>True = False
>>>True
False
You can really make someone become crazy with this one.
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
#define true false
but only if stdbool.h is used.
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
Oracle has a couple of SQL WTF issues.
Oracle's treatment of empty strings as null.
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.
''
should no more be treated as NULL than should the integer 0
.
Jan 5, 2010 at 0:31
Java has a whole freakin book about them.
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.
cursor:pointer
(or something like that)
(function(){})()
, with the parentheses in different places
tabindex=0
to those elements, otherwise they won't be keyboard-accessible.
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.
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" }
ack '\.{3}'
Aug 15, 2010 at 14:27
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 theDO
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.
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.
implicit none
is backported to a number of fortran 77 compilers too.
Jan 8, 2010 at 4:29
DO10I=1.10
and D O 1 0 I = 1 . 1 0
are treated the same!
May 2, 2010 at 16:28
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.
http:
is a GOTO label, it defines a position in the current scope you can jump to by calling goto http;
.
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.
<:-D>..</:-D>
as tag. Great, I'm going to abuse this immediately!
C
) to the smiley face it should be valid? <o_o>OMG</o_o>
is directly valid tho'
<
(which I assume is supposed to be text content) is illegal. How about <_><_·.>:/:>_.·</_·.></_>
Inheriting from random class in Ruby:
class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].sample
...
end
(first seen at Hidden features of Ruby)
class C ( random.choice([A, B]) ):
;-)
Jan 12, 2010 at 6:46
package C; use base (qw/A B/)[ int(rand(2)) ];
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'
isa
/ class_pointer
is changed to the newly created subclass.
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
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
(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
In ruby/python/c, you can concatenate strings just like this:
a = "foo" "bar"
print a # => "foobar"
@""
), you don't need any extra @s. For example, @"foo" "bar"
. This can be really useful for breaking strings across lines...
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.
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
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)))
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.)
Tri-valued logic of nulls
in ANSI SQL.
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]]
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.
parseInt(x, 10)
is about 3 times slower than Math.floor()
.
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.
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
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."
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
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:
Java; making all object instances be mutexes.
synchronized
statement would be a lot harder to use if that wasn't the case.
Jan 5, 2010 at 1:03
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.
In PHP one can do:
System.out.print("hello");
UndefinedConstant
as "UndefinedConstant"
)
"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.
Dec 15, 2011 at 23:04
In JavaScript:
alert(111111111111111111111) // alerts 111111111111111110000
This was quite damaging to some 64bit keys I passed back and forth in JSON.
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
else
is only executed if the for
loop does not exit because of a break
statement.
Sep 11, 2010 at 13:05
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)
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
return l.append(1)
. You have to l.append(1); return l
because list.append
returns nothing.
Jan 6, 2010 at 5:45
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.