为什么 C++在这个简单的程序中,编译器没有给出优先级(赋值下的递增运算符)?
根据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
我做错了什么?
According to the table of precedence of operators in C/C++ language (see Wikipedia), the increment operator (++) takes precedence with respect to the assignment operator (=).
Can someone explain why the compiler first assign the value (1 in bill[x]) and then increases the index value (i++) in this simple program. I think it should be the opposite (first increase and then assign):
#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;
}
The output is:
16
17
18
1
20
Index value:4
I'm doing something wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
i
正在递增,但不是在它用作数组访问器之前。要获得您正在寻找的内容,请尝试使用++i
。 (前缀而不是后缀。)i
is being incremented, but not before it is used as the array accessor. To get what you're looking for, try++i
instead. (Prefix instead of postfix.)您可以用另一种方式来看待这个问题:
您可以将其读作先递增“i”,然后执行该语句。
您可以将其理解为,首先执行语句,然后递增“i”。
如果您想知道这是如何实现的,可以像这样实现内部后增量以获得您所看到的行为:
与预增量相比,如下所示:
Another way you can look at this:
You can read it as, increment 'i' first then do the statement.
You can read it as, first do the statement then increment 'i'.
If you're wondering how this is possible, internally post-increment can be implemented like this to get the behavior you're seeing:
vs pre-increment which looks like this:
“i++”的意思是,
“使用增量之前的变量值作为表达式结果,但增量变量”。
“++i”的意思是“增加变量,并使用增加后的值作为结果”。
"i++" means,
"use as the expression result, the variable value before the increment, but increment the variable".
"++i" means, "increment the variable, and use the incremented value as the result".
首先完成增量。但是,
i++
会递增i
并返回旧值的副本。正如其他人提到的,要获得所需的行为,请使用++i
,它会递增i
并返回对i
的引用。The increment is being done first. However,
i++
incrementsi
and returns a copy of the old value. As others have mentioned, to get the desired behaviour, use++i
, which incrementsi
and returns a reference toi
.