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

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


当前回答

有趣的自动装箱和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;

其他回答

早期的FORTRAN,空格不重要。(anti-Python !)

DO 20 I = 1, 10

含义:从这里循环到第20行,I从1到10。

DO 20 I = 1. 10

含义:将1.10分配给名为DO20I的变量。

有传言说这个漏洞毁了一个太空探测器。

在Common Lisp中,零维数组是很奇怪的,而且很自然地,它们具有读取语法。

? (aref #0A5)
5

我认为这实际上不是一个“语言特性”(C),我很可能在发布它时很无知,但我不知道为什么会发生这种情况,所以我会问。如果它被证明与一些奇怪的语言特征有关…这真的让我很不爽,所以这个地方是值得的。

int a = 0;
int *p = &a;

printf("%d, %d, %d.\n", *p, (*p)++, *p); // Outputs "1, 0, 0.\n" on MinGW's GCC 4.4.1

Why?

——编辑

刚拿到的,没什么大不了的。我能感觉到c++大师们现在在嘲笑我。我猜函数参数计算的顺序是未指定的,所以编译器可以自由地调用它们(我想我已经在boost的文档中读到过)。在本例中,实参语句是向后求值的,这可能反映了函数的调用约定。

在C:

int main() {
  int i = 0;
  int array[] = {1,2};

  return (i[array] + 1 == array[i]);
}

这个程序将返回1 (true)。

在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();
}