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

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


当前回答

Python for循环中的else。

来自Python文档:

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'

输出:

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

其他回答

C / C + +:

快速平方根逆算法利用了IEEE浮点表示法(代码复制自维基百科):

float InvSqrt(float x)
{
    union {
        float f;
        int i;
    } tmp;
    tmp.f = x;
    tmp.i = 0x5f3759df - (tmp.i >> 1);
    float y = tmp.f;
    return y * (1.5f - 0.5f * x * y * y);
}

在Java中从文本文件中读取一行。

BufferedReader in = null;
try {
   in = new BufferedReader(new FileReader("filename"));
   String str;
   str = in.readLine();
   if (str != null) {
      ...
   } 
} catch (IOException e) {
   ...
} finally {
   try {
      if (in != null) {
         in.close();
      }
   } catch (IOException e) {}
}

啊。虽然我承认这并不奇怪……只是邪恶。: -)

更短、更习惯的版本:

try {
   BufferedReader in = new BufferedReader(new FileReader("filename"));
   try {
       String str = in.readLine();
       while (str != null) {
          str = in.readLine();
       } 
    } finally {
        in.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}

这可能已经被提到了,但是——

PHP对八进制值的处理:

$a = 07; // 7 (as it should be)
$b = 08; // 0 (would be an error in any sensible language)
$c = 018; // 1 (again, should have been an error)
$d = 0A; // error (as it should be)

请看这里:http://bugs.php.net/bug.php?id=29676

还要注意关于这个错误的评论——Derick称其为一个特性(引用“fix”表示),而不是一个错误,他声称它会“在脚本中使用数字的所有情况下显著降低PHP的速度”——但是,为什么PHP会引发一个0A错误呢?

我认为人们可以写一整本书来讲述PHP的古怪之处……

在PHP中:

for ($s="a";$s<="z";$s++) echo $s.' ';

这将是:

a b c d e .. .w x y z aa ab ac ad .. ay az ba bb bc ... by bz ca cb ... yz za zb ... zx zy zz

在Perl中,可以通过修改一个类的@ISA数组来改变它的继承链,这让我很惊讶。

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'