根据C/C++语言的运算符优先级表(参见维基百科),自增运算符(++)优先于赋值运算符(=)。
谁能解释为什么在这个简单的程序中编译器首先分配值(bill[x] 中的 1)然后增加索引值(i++)。我觉得应该是相反的(先增加再赋值):
#include <iostream>
using namespace std;
int bill[] = {16, 17, 18, 19, 20};
int main ()
{
int i = 3;
bill[(i++)] = 1; // I think it should be bill[4] = 1;
cout << bill[0] << endl;
cout << bill[1] << endl;
cout << bill[2] << endl;
cout << bill[3] << endl;
cout << bill[4] << endl;
cout << "Index value:" << i << endl;
return 0;
}
输出是:
16
17
18
1
20
Index value:4
我做错了什么?
最佳答案
i
正在递增,但在它用作数组访问器之前不会递增。要得到你要找的东西,试试 `++i' 代替。 (前缀而不是后缀。)
关于c++ - 为什么 C++ 编译器在这个简单的程序中不给予优先权(赋值下的递增运算符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380960/