C++访问数组的元素

C++ accessing elements of an array

本文关键字:元素 数组 访问 C++      更新时间:2023-10-16

通常我们以这种方式访问数组元素:arrayName[elementID]。但即使我们像elementID[arrayName]一样使用它,它也会编译,并且在运行时不会导致任何错误。这在逻辑上不是错的吗?有人能给我解释一下吗。我是C++新手。提前感谢您的帮助!

#include<iostream>
using namespace std;
int main()
{
    int arr[4] = {2, 4, 5, 7};
    cout << arr[2] << endl; //this is the correct way to use it 
    cout << 2[arr] << endl; //this gives the same result and does not cause any errors
    return 0;
}

以下等效:

a[b] == *(a + b) == *(b + a) == b[a]

使用哪一个并不重要,只要它可读并且传达了程序员的意图。