今天翻前兩天剛送到的《C專家編程》,章節(jié)8.10的那個IOCCC 1987年的獲獎作品讓我覺得很好玩。
main(){ printf(&unix["/021%six/012/0"], (unix)["have"] + "fun" - 0x60);}
作者這里利用的第一個技巧并不算太晦澀:"a[i] = i[a]= *(a+i)“ 即下標運算符的可交換性。
但是這個老天爺?shù)膗nix和&unix是怎么回事?
我把自己腦子里有印象的C的最隱蔽的角落回想了一遍,難道是trigraph之類的特殊符號?查了查不是
正推不行,就反推吧。編譯運行后,輸出結(jié)果是“unix“。如此說來“(unix)["have"] + "fun" - 0x60)“這個表達式的結(jié)果應(yīng)該是指向"un"的char * ;因此,“(unix)["have"] - 0x60"的值應(yīng)該是整數(shù)1才對;因此“(unix)["have"]"的值應(yīng)該是0x61;這就豁然開朗了,0x61='a',是"have"中的第二個字符,所以unix的值必然為1。
這個反推是否正確呢? 利用gcc看一下只進行preprocessor處理后的代碼:
whodare@whodare:~/programming/c++$ gcc -E 1.c
main()
{
printf(&1["/021%six/012/0"], (1)["have"] + "fun" - 0x60) ;
}
正確。unix看來是屬于預(yù)定義的marco,值為1。拿“gcc predefined marco"為關(guān)鍵字google了一下,找到可信資料了:
http://gcc.gnu.org/onlinedocs/cpp/System_002dspecific-Predefined-Macros.html#System_002dspecific-Predefined-Macros
原來unix這個宏是屬于gcc提供的 System-specific Predefined Macros,因此這個奇妙的函數(shù)只能在*nix環(huán)境下正常工作。
可以查看更多的gcc提供的predefined marco
gcc -dM -E 1.c
順便附上歷史文獻,哈哈
Best One Liner:
David Korn
Bell Labs
MH 3C-526B, AT&T Bell Labs
Murray Hill, NJ
07974
USA
The Judges believe that this is the best one line entry ever received.
Compile on a UN*X system, or at least using a C implementation that
fakes it. Very few people are able to determine what this program
does by visual inspection. I suggest that you stop reading this
section right now and see if you are one of the few people who can.
Several points are important to understand in this program:
What is the symbol `unix' and what is its value in the program?
Clearly `unix' is not a function, and since `unix' is not declared
to be a data type (such as int, char, struct foo, enum, ...)
what must `unix' be?
What is the value of the symbol "have"? (hint: the value is
NOT 4 characters, or 'h', or a string) Consider the fact that:
char *x;
defines a pointer to a character (i.e. an address), and that
the `=' assigns things is compatible types. Since:
x = "have";
is legal C, what type of value is "have"?
Note that the following expressions yield the same value:
+ "fun" - 0x60)
*(x+3) *(3+x)
since addition is communitive. What can be said about the value:
3[x]
本文授權(quán)轉(zhuǎn)載自公眾號“技術(shù)讓夢想更偉大”,作者李肖遙
免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺僅提供信息存儲服務(wù)。文章僅代表作者個人觀點,不代表本平臺立場,如有問題,請聯(lián)系我們,謝謝!