代码改变世界

一小段乱码的分析[原创]

2007-01-15 21:45  老博客哈  阅读(1320)  评论(3编辑  收藏  举报
闲来无事, 逛了逛hit的forum, 看到有个人的签名挺有趣的。
main(int _){for(--_;putchar(_++["Ibqqz!Ofx!Zfbs\"\1"]-1););} 

初看上去, 一点头续都没有。
int main()
{
     
int i = 0;
     
for(; putchar(i["Ibqqz!Ofx!Zfbs\"\1"]-1) ; ++i )
           ;
     
return 0;
}

这时候发现核心部分就在putchar地方。


这个写法i["Ibqqz!Ofx!Zfbs\"\1"] 看懂了吗?
我当时没有看懂, 大汗。。。
真当百思不得其解的时候, 我依稀记得pfan上有人有过这种“特殊的”写法,
遂打开了MSDN, 索引里面顺手打了[]进行简索。
没想到还真有, hoho, 看了一下, 什么疑云都没了。
我就先摘过来:

A postfix expression (which can also be a primary expression) followed by the subscript operator, [ ], specifies array indexing.

For information about managed arrays, see array.

Usually, the value represented by postfix-expression is a pointer value, such as an array identifier, and expression is an integral value (including enumerated types). However, all that is required syntactically is that one of the expressions be of pointer type and the other be of integral type. Thus the integral value could be in the postfix-expression position and the pointer value could be in the brackets in the expression or subscript position. Consider the following code fragment:

Copy Code
  int nArray[5] = { 0, 1, 2, 3, 4 };
  cout << nArray[2] << endl;         // prints "2"
  cout << 2[nArray] << endl;         // prints "2"



In the preceding example, the expression nArray[2] is identical to 2[nArray]. The reason is that the result of a subscript expression e1[ e2 ] is given by:

*( (e2) + (e1) )


好了, 看懂了吗?
如果没有, 我就简单的说明一下,
一个对char *的数据类型, 用[]运算时,
index和它本身的位置可以互换的。
即: nArray[2] 和 2[nArray] 是一样的(ps:nArray是 char * const )
之所以等价是因为, 编译器对它的解释:
a[b] <========> *((a) +(b))

所以上面的程序就是:
int main()
{
     
int i = 0;
     
for(; putchar("Ibqqz!Ofx!Zfbs\"\1"[i]-1) ; ++i )
           ;
     
return 0;
}
 


写的好看一点就是这样:
int main()
{
     
int i = 0;
     
char *str = "Ibqqz!Ofx!Zfbs\"\1";
     for(; putchar(str[i]-1) ; ++i )
           ;
     
return 0;
}