在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
当前回答
在JavaScript中,你可以使用双位负(~~n)来代替Math.floor(n)(如果n是正数)或parseInt(n, 10)(即使n是负数)。N | N和N & N总是得到和~~ N相同的结果。
var n = Math.PI;
n; // 3.141592653589793
Math.floor(n); // 3
parseInt(n, 10); // 3
~~n; // 3
n|n; // 3
n&n; // 3
// ~~n works as a replacement for parseInt() with negative numbers…
~~(-n); // -3
(-n)|(-n); // -3
(-n)&(-n); // -3
parseInt(-n, 10); // -3
// …although it doesn’t replace Math.floor() for negative numbers
Math.floor(-n); // -4
单个位的求反(~)计算-(parseInt(n, 10) + 1),因此两个位的求反将返回-(-(parseInt(n, 10) + 1) + 1)。
更新:这里有一个jsPerf测试用例,比较了这些替代方案的性能。
其他回答
这并不是说它被大量使用,而是c++的“返回对静态大小数组的引用”的语法很奇怪:
struct SuperFoo {
int (&getFoo() const)[10] {
static int foo[10];
return foo;
}
}
在上述情况下,Ofc方法可以声明为静态const
Perl的许多内置变量:
$# — not a comment! $0, $$, and $? — just like the shell variables by the same name $ˋ, $&, and $' — weird matching variables $" and $, — weird variables for list- and output-field-separators $! — like errno as a number but strerror(errno) as a string $_ — the stealth variable, always used and never seen $#_ — index number of the last subroutine argument... maybe @_ — the (non)names of the current function... maybe $@ — the last-raised exception %:: — the symbol table $:, $^, $~, $-, and $= — something to do with output formats $. and $% — input line number, output page number $/ and $\ — input and output record separators $| — output buffering controller $[ — change your array base from 0-based to 1-based to 42-based: WHEEE! $} — nothing at all, oddly enough! $<, $>, $(, $) — real and effective UIDs and GIDs @ISA — names of current package’s direct superclasses $^T — script start-up time in epoch seconds $^O — current operating system name $^V — what version of Perl this is
还有很多这样的东西。点击这里阅读完整列表。
Duff的C语言设备!
在C语言中,可以将do/while语句与switch语句交错使用。下面是memcpy使用此方法的示例:
void duff_memcpy( char* to, char* from, size_t count ) {
size_t n = (count+7)/8;
switch( count%8 ) {
case 0: do{ *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
}while(--n>0);
}
}
Perl充满了奇怪但整洁的特性。
If可以用在语句之前或之后,就像这样:
print "Hello World" if $a > 1;
if ($a > 1) { print "Hello World"; }
foreach也是如此:
print "Hello $_!\n" foreach qw(world Dolly nurse);
Common Lisp的format函数有一个选项,可以将数字打印为罗马数字。
在INTERCAL中,这是你能得到的唯一输出形式。