細數那些令人發狂的程序語言的特性
1
這些最為奇怪的程序語言的特性,來自stackoverflow.com,原貼在這里。我摘選了一些例子,的確是比較怪異,讓我們一個一個來看看。
1、C語言中的數組
在C/C++中,a[10] 可以寫成 10[a]
“Hello World”[i] 也可以寫成 i["Hello World"]
2、在JavaScript中
’5′ + 3 的結果是:’53′
’5′ – 3 的結果是:2
3、C/C++中的Trigraphs
int main() { cout << "LOL??!"; }
上面的這段程序會輸出: “LOL|”,這是因為 ??! 被轉成了 | ,關于Trigraphs,下面有個表格:
??= | # |
??( | [ |
??/ | \ |
??) | ] |
??’ | ^ |
??< | { |
??! | | |
??> | } |
??- | ~ |
4、JavaScript 的條件表
看到下面這個表,不難理解為什么Javascript程序員為什么痛苦了。
'' == '0' //false 0 == '' //true 0 == '0' //true false == 'false' //false false == '0' //true false == undefined //false false == null //false null == undefined //true " \t\r\n" == 0 //true
5、JAVA的Integer Cache
Integer foo = 1000; Integer bar = 1000; foo <= bar; // true foo >= bar; // true foo == bar; // false //然后,如果你的 foo 和 bar 的值在 127 和 -128 之間(包括) //那么,其行為則改變了: Integer foo = 42; Integer bar = 42; foo <= bar; // true foo >= bar; // true foo == bar; // true
為什么會這樣呢?你需要了解一下Java Interger Cache,下面是相關的程序,注意其中的注釋。
/** * 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 * <a href="mailto:{@link">{@link</a> #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); }
其所有的這些怪異的變量請參看:http://www.kichwa.com/quik_ref/spec_variables.html
6、Java的異常返回
請看下面這段程序,你覺得其返回true還是false?
try { return true; } finally { return false; }
在 javascript 和Python下,其行為和Java的是一樣的。
7、C語言中的Duff device
下面的這段程序你能看得懂嗎?這就是所謂的Duff Device,相當的怪異。
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); } }
8、PHP中的字符串當函數用
PHP中的某些用法也是很怪異的
$x = "foo"; function foo(){ echo "wtf"; } $x();
9、在C++中,你可以使用空指針調用靜態函數
class Foo { public: static void bar() { std::cout << "bar()" << std::endl; } };
呵呵。的確是挺怪異的。