<分区>
任何人都可以向我解释为什么这是可能的吗?。 我知道 a 与 &a[0] 相同,例如我也明白 *(a+1) 是第二个元素,我可以使用 *((a+i)+j) 技术,但我一生中第一次看到这样的代码,现在我很困惑。 我知道输出是数组的第四个元素。但是谁能向我解释为什么这是可能的?
#include<iostream>
int a[] = {1,2,3,4,5};
std::cout << (3)[a] << std::endl;
<分区>
任何人都可以向我解释为什么这是可能的吗?。 我知道 a 与 &a[0] 相同,例如我也明白 *(a+1) 是第二个元素,我可以使用 *((a+i)+j) 技术,但我一生中第一次看到这样的代码,现在我很困惑。 我知道输出是数组的第四个元素。但是谁能向我解释为什么这是可能的?
#include<iostream>
int a[] = {1,2,3,4,5};
std::cout << (3)[a] << std::endl;
最佳答案
二进制表达式:
x[y]
被定义为等于:
*(x+y)
(在没有 operator []
重载的情况下)。
3+a
与 a+3
相同,所以 3[a]
与 a[3] 相同
。
在 3+a
的上下文中,数组 a
的名称衰减为指向其第一个元素的指针,因此我们尝试添加一个指针和一个整数使用内置的加法运算符。 The latest draft of C++14在第 5.7 节 [expr.add] 第 4 段中说:
When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist
这与 C++14 标准的文本非常接近,但这种行为自 C89 以来一直稳定(实际上自 70 年代的 BCPL 以来)。
话虽如此,如果您找到这样的代码,请找到作者并用线索 Racket 打他的脑袋。编写 C++ 非常容易,没有人(包括一周后的你自己)可以阅读 - 这对任何人都没有用。
关于关于数组的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292114/