在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?

请每个回答只回答一个特征。


当前回答

在JavaScript中,下面的构造

return
{
    id : 1234,
    title : 'Tony the Pony'
};

返回undefined是一个语法错误,因为在返回后的换行上偷偷地插入了分号。以下工作正如你所期望的那样:

return {
    id : 1234,
    title : 'Tony the Pony'
};

更糟糕的是,这个也可以(至少在Chrome中):

return /*
*/{
    id : 1234,
    title : 'Tony the Pony'
};

下面是同一个问题的一个变种,它不会产生语法错误,只是无声地失败了:

return
    2 + 2;

其他回答

COMEFROM是我见过的最奇怪,也可能是最没用的语言功能。

其次是三元运算符,因为它违反了优化的第一条规则。它带来的危害大于它解决的问题。它的危害更大,因为它使代码可读性更差。

并不是一个真正的语言功能,但有趣/很棒的功能使用是Duff的设备。

In C

a[i++] = i;

它会编译,但很少执行您认为它应该执行的操作。优化更改会产生截然不同的结果。它在不同平台上的运行方式也不同。

然而,编译器对此非常满意。

INTERCAL可能是最奇怪的语言特征的最佳汇编。我个人最喜欢的是COMEFROM语句,它(几乎)与GOTO相反。

COMEFROM is roughly the opposite of GOTO in that it can take the execution state from any arbitrary point in code to a COMEFROM statement. The point in code where the state transfer happens is usually given as a parameter to COMEFROM. Whether the transfer happens before or after the instruction at the specified transfer point depends on the language used. Depending on the language used, multiple COMEFROMs referencing the same departure point may be invalid, be non-deterministic, be executed in some sort of defined priority, or even induce parallel or otherwise concurrent execution as seen in Threaded Intercal. A simple example of a "COMEFROM x" statement is a label x (which does not need to be physically located anywhere near its corresponding COMEFROM) that acts as a "trap door". When code execution reaches the label, control gets passed to the statement following the COMEFROM. The effect of this is primarily to make debugging (and understanding the control flow of the program) extremely difficult, since there is no indication near the label that control will mysteriously jump to another point of the program.

在Java中,

String s = null;
System.out.println(s + "hello");

输出“nullhello”。

JavaScript中的变量赋值可以创建全局变量。如果一个变量在函数中被赋值,并且没有在相同的作用域中声明为var,那么它将隐式声明为global。

function foo() {
  x = "juhu";  // creates a global variable x!
  var y = "kinners"
}

foo();
alert(x); // alerts "juhu"
alert(y); // alerts undefined

注意,var语句也可以在给变量赋值后使用:

function foo() {
  x = 12;
  var x; // x is now local
  return x;
}

alert(foo()); // will alert 12;
alert(x); // will alert undefined