[英]Why the C++ compiler does not give precedence (increment operator under assignment) in this simple program?
根據C / C ++語言中運算符的優先級表(參見Wikipedia),增量運算符(++)優先於賦值運算符(=)。
有人可以解釋為什么編譯器首先分配值(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'。 (前綴而不是后綴。)
另一種你可以看到的方式:
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; // access bill[3] even though i == 4
vs pre-increment,如下所示:
int pre_increment(int &i)
{
i = i + 1;
return i;
}
bill[pre_increment(i)] = 1; // access bill[4] where i == 4
“i ++”表示“用作表達式結果,增量前的變量值,但增加變量”。
“++ i”表示“遞增變量,並使用遞增的值作為結果”。
增量被首先進行。 但是, i++
遞增i
並返回舊值的副本。 正如其他人所提到的,為了獲得所需的行為,使用++i
,它增加i
並返回對i
的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.