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

标签 c++ arrays c square-bracket subscript-operator

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

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/

相关文章:

sizeof 与 chars 的混淆行为

c++ - 在单个分配中分配一个包含字符串的结构

c++ - Type_traits *_v 变量模板实用程序顺序编译失败

ios - 使用swift在UITableView中有UITextFields时如何管理键盘?

python - 为什么 numpy.zeros 占用空间小

c - 将结构发送到先前用指针定义的函数

c - C代码格式化

c++ - 这个变量赋值有什么不同?

c++ - 获取第n个斐波那契数的简单代码

c - 初始化矩阵,C 中的预期表达式错误