gpt4 book ai didi

c++ - 在 C 和 C++ 中通过 index[array] 访问数组

转载 作者:IT老高 更新时间:2023-10-28 12:33:18 25 4
gpt4 key购买 nike

有些面试官出于某种原因喜欢问这个小技巧问题:

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 that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

它没有说明要求 [] 的参数顺序保持正常。

关于c++ - 在 C 和 C++ 中通过 index[array] 访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5073350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com