有些面试官出于某种原因喜欢问这个小技巧问题:
int arr[] = {1, 2, 3};
2[arr] = 5; // does this line compile?
assert(arr[2] == 5); // does this assertion fail?
据我所知, a[b]
被转换为 *(a + b)
并且由于加法是可交换的,因此它们的顺序并不重要,所以 2[a]
真的是 *(2 + a)
并且工作正常。
这是否保证符合 C 和/或 C++ 的规范?
最佳答案
是的。 6.5.2.1 第 1 段(C99 标准)描述了 []
运算符的参数:
One of the expressions shall have type "pointer to object
type
", the other expression shall have integer type, and the result has type "type
".
6.5.2.1 第 2 段(强调添加):
A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
-th element ofE1
(counting from zero).
它没有说明要求 []
的参数顺序保持正常。
关于c++ - 在 C 和 C++ 中通过 index[array] 访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5073350/