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

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


当前回答

我肯定会给Perl提供多个可怕的例子:

if(!$#var)

or

if($mystring =~ m/(\d+)/) {

其他回答

有向图和替代标记

C (ISO/IEC 9899:1999, 6.4.6/3)和c++ (ISO/IEC 14882:2003, 2.5)有一个很少使用的特性,被C称为“有向图”,被c++称为“替代令牌”。它们不同于三trigraph,主要是因为包含它们的字符串字面量永远不会被不同地解释。

%:include <stdio.h>

int main() <%
    int a<:10:> = <%0%>;
    printf("Here's the 5th element of 'a': %d\n", a<:4:>);
    puts("Evil, eh? %:>");
    return 0;
%>

c++有更多,包括and, or, and not,它们被要求表现为&&,||和!C语言也有这些,但是需要包含<iso646.h>来使用它们,将它们视为宏而不是令牌。c++头文件<ciso646>实际上是一个空文件。

值得注意的是,GCC实现了对这种奇怪的语言特性的支持,但许多其他编译器在尝试编译上述代码段时都阻塞并死亡。

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

С#:

var a = Double.Parse("10.0", CultureInfo.InvariantCulture); // returns 10
var b = Double.Parse("10,0", CultureInfo.InvariantCulture); // returns 100

在不变区域性中,逗号不是小数点符号,而是组分隔符。

据我所知,对于一些地区的新手程序员来说,这是一个常见的错误。

有趣的自动装箱和Java中的整数缓存:

Integer foo = 1000;
Integer bar = 1000;

foo <= bar; // true
foo >= bar; // true
foo == bar; // false

//However, if the values of foo and bar are between 127 and -128 (inclusive)
//the behaviour changes:

Integer foo = 42;
Integer bar = 42;

foo <= bar; // true
foo >= bar; // true
foo == bar; // true

解释

快速浏览一下Java源代码将会出现以下内容:

/**
 * Returns a <tt>Integer</tt> instance representing the specified
 * <tt>int</tt> value.
 * If a new <tt>Integer</tt> instance is not required, this method
 * should generally be used in preference to the constructor
 * {@link #Integer(int)}, as this method is likely to yield
 * significantly better space and time performance by caching
 * frequently requested values.
 *
 * @param  i an <code>int</code> value.
 * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

注意:IntegerCache。High默认为127,除非由属性设置。

自动装箱的情况是,foo和bar都是从缓存中检索到相同的整数对象,除非显式创建:例如,foo = new integer(42),因此在比较引用是否相等时,它们将为真而不是假。比较Integer值的正确方法是使用.equals;

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

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

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