首页 > 解决方案 > 奇怪的 operator[] 行为

问题描述

在写程序的时候,我打错了。我已经写i[data]data[i]。但是,该程序已成功编译并正常运行。

Operator[] 对数组的行为:

#include <iostream>

using namespace std;

int main()
{
  int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
  cout << data[6] << endl; // prints 6
  cout << 6[data]; // prints 6
  return 0;
}

与指针类似的 operator[] 行为:

#include <iostream>

using namespace std;

int main()
{
  char* str = "Hello, world!";
  
  cout << str[9] << endl; //prints 'r'
  cout << 9[str]; //prints 'r'
  return 0;
}

为什么data[i]等于i[data]

标签: c++operators

解决方案


i[data]是相同的*(i + data)

data[i]是相同的*(data + i)

并且data + i等于i + data


推荐阅读