最丑的女明星是谁:原来代码可以这么写 --记性不好的matthew
来源:百度文库 编辑:中财网 时间:2024/04/26 13:36:03
今天在google groups 的comp.lang.c++邮件列表里看到这么一段代码,真是有意思,我是第一次看到这种代码。
#include
int main()
{
int arr[3] = {1, 2, 3};
for (int i = 0; i < 3; ++i)
std::cout << i[arr] << " ";
std::cout << std::endl;
for (int j = 0; j < 3; ++j)
std::cout << arr[j] << " ";
std::cout << std::endl;
return 0;
}
据说是利用了加法的交换性和传递性(commutativity and transitivity of addition)。
推导过程:
[quote]
.......
int main()
{
int arr[3] = {1, 2, 3};
for (int i = 0; i < 3; ++i)
std::cout << i[arr] << " ";
std::cout << std::endl;
for (int j = 0; j < 3; ++j)
std::cout << arr[j] << " ";
std::cout << std::endl;
return 0;
}
据说是利用了加法的交换性和传递性(commutativity and transitivity of addition)。
推导过程:
[quote]
.......
Using the transitivity of addition (meaning that A+B == B+A) we can
get some pretty ugly, but valid, syntax when indexing into arrays:
So arr[N] == *(arr + N) then we apply the transitivity rule on the
left hand giving *(N + arr) and then go back to the array-form gives
N[arr].
So given array arr then 2[arr] will give the third element in arr. And
then we replace the N with a variable and we get something like this:
int main()
{
int arr[3] = {1, 2, 3};
for (int i = 0; i < 3; ++i)
std::cout << i[arr];
return 0;
}
[/quote]
原文:
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/599be6c63ddaba57?hl=en