在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
当前回答
在(MRI/C) Ruby和MacRuby(而不是JRuby)中,整洁的系统相关溢出会导致年份翻转,然后出现更大数量的本地时间错误。这不是一个常见的问题,但很奇怪:
$ ruby -version
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
$ irb
>> Time.at(67767976233550799)
=> Tue Dec 31 23:59:59 -0500 2147483647
>> Time.at(67767976233550800)
=> Wed Jan 01 00:00:00 -0500 -2147483648
>> Time.at(67768036191694799)
=> Wed Dec 31 23:59:59 -0500 -2147481749
>> Time.at(67768036191694800)
ArgumentError: localtime error
...
Maybe IRB bug!!
不过,这可能特定于64位环境。
其他回答
我最喜欢的奇怪的C语言是5[“Hello World”],但因为已经发布了,我最喜欢的第二个奇怪的是Windows版本结构初始化黑客:
void someWindowsFunction() {
BITMAPINFOHEADER header = {sizeof header};
/* do stuff with header */
}
这条微妙的线条达到了以下效果:
Declares a BITMAPINFOHEADER structure Concisely sets the "size" member of the structure, without hardcoding a size constant (since many Window structures, including BITMAPINFOHEADER, follow the convention of specifying the size of the structure as the first member} Declares the version of the structure (since many Windows structures, including BITMAPINFOHEADER, identify their version by the declared size, following the convention that structures definitions are append-only) Clears all other members of the structure (a C standard behavior when a structure is incompletely initialized).
在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'
在C语言中,sizeof操作符不计算其实参。这允许编写看起来错误但实际上是正确的代码。例如,给定类型T,调用malloc()的惯用方法是:
#include <stdlib.h>
T *data = NULL;
data = malloc(sizeof *data);
这里,*data在sizeof操作符中不被求值(data是NULL,所以如果它被求值,就会发生糟糕的事情!)。
这使得人们能够编写令人惊讶的代码,无论如何,对于新手来说。请注意,没有哪个头脑正常的人会这么做:
#include <stdio.h>
int main()
{
int x = 1;
size_t sz = sizeof(x++);
printf("%d\n", x);
return 0;
}
输出1,而不是2,因为x永远不会增加。
对于sizeof的一些真正的乐趣/困惑:
#include <stdio.h>
int main(void)
{
char a[] = "Hello";
size_t s1 = sizeof a;
size_t s2 = sizeof ("Hi", a);
printf("%zu %zu\n", s1, s2);
return 0;
}
(只有当人们对数组、指针和操作符感到困惑时才会出现这种困惑。)
在C中,a[b][C]与C [b[a]]完全相同。
Python的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]]