为什么C ++编译器在这个简单的程序中不给予优先级(在赋值下增量运算符)? [英] Why the C++ compiler does not give precedence (increment operator under assigment) in this simple program?
问题描述
根据C / C ++语言中操作符的优先级表(见维基百科),增量运算符(++)优先于赋值运算符(=)。
有人可以解释为什么编译器首先分配值(1在bill [x]),然后增加索引值(i ++)在这个简单的程序。我认为应该是相反的(首先增加然后分配):
#include< iostream>
using namespace std;
int bill [] = {16,17,18,19,20};
int main()
{
int i = 3;
bill [(i ++)] = 1; //我认为应该是bill [4] = 1;
cout<< bill [0]< endl
cout<< bill [1]< endl
cout<< bill [2]< endl
cout<< bill [3]< endl
cout<< bill [4]< endl
cout<< 索引值:< i<< endl
return 0;
}
输出为:
16
17
18
1
20
索引值:4
$ c $ 解决方案
p>另一种方式你可以看看这: bill [(++ i)] = 1;
您可以读取它,先增加'i'然后执行语句。
bill [(i ++)] = 1;
您可以读取它,先做语句,然后增加'i'。
如果你想知道这是怎么可能的,内部后增量可以像这样实现你所看到的行为:
int post_increment(int& i)
{
int t = i;
i = i + 1;
return t;
}
bill [post_increment(i)] = 1; //访问bill [3]即使i == 4
:
int pre_increment(int& i)
{
i = i + 1;
return i;
}
bill [pre_increment(i)] = 1; // access bill [4]其中i == 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?
解决方案 Another way you can look at this:
bill[(++i)] = 1;
You can read it as, increment 'i' first then do the statement.
bill[(i++)] = 1;
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:
int post_increment(int &i)
{
int t = i;
i = i + 1;
return t;
}
bill[post_increment(i)] = 1; // access bill[3] even though i == 4
vs pre-increment which looks like this:
int pre_increment(int &i)
{
i = i + 1;
return i;
}
bill[pre_increment(i)] = 1; // access bill[4] where i == 4
这篇关于为什么C ++编译器在这个简单的程序中不给予优先级(在赋值下增量运算符)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!