[英]Pre increment and post increment
我無法理解后增量( ++
),預增量( --
)和加法/減法如何在一個例子中協同工作。
x++
表示將1添加到變量中。
x--
表示從變量中減去1。
但我對這個例子感到困惑:
int x = 2, y = 3, z = 1;`
y++ + z-- + x++;
我假設這意味着3(+1) + 1(-1) + 2(+1)
這意味着結果應該是7。
但是當我編譯它時,我得到6
。 我不明白。
int main() {
int x=2, y=3, z=1;
int result;
result = y++ + z-- + x++; //this returns 6
cout << result << endl;
return 0;
}
因為后綴operator++
在遞增變量之前返回原始值。 前綴operator++
增加varialbe並返回對它的引用。 可以通過示例輕松說明該行為:
#include <iostream>
int main()
{
int n = 1;
std::cout << n++ << "\n"; // prints 1
std::cout << n << "\n"; // prints 2
int m = 10;
std::cout << "\n";
std::cout << ++m << "\n"; // prints 11
std::cout << m << "\n"; // prints 11
}
result = y++ + z-- + x++;
3 1 2 = 6
如果再次執行此操作
result1 = y++ + z-- + x++;
4 0 3 = 7
原因
operator++
在遞增變量之前返回原始值。
和
++operator
返回遞增的值
--
與上面相同的是它的減量
當你寫x++
,它使用的當前值x
,然后由一個增加它。
如果你想先增加,你想寫++x
。
Pre-increment operator(++p)
首先增加該值並賦值,然后post increment operator(p++)
首先賦值,然后執行增量運算。這里所有變量都是后增量,即它最初賦值(在緩沖區上)然后增加(對於y和x乘以1)並將z減小1.即最初在緩沖區中分配3 + 1 + 2(對緩沖區值執行加法)然后執行遞增/遞減,因為x = 3,y = 4且z = 0
有關更多信息,您可以閱讀答案cout << c ++ << c ;?的正確答案是什么? 為什么這些構造(使用++)未定義的行為? 問題
原因很簡單。 這里使用關聯原則,它根據運算符的優先級計算值。
也是X++
或X--
表示......使用然后改變...它將首先使用該值並增加或減少它。 如果你想得到7
的輸出......試試這個......它可能會起作用......
result = ++y + z-- + x++;
后增量/后增量將增加/減少變量,但會計算變量的“先前”值。
所以表達式result = y++ + z-- + x++
將表現得像:
result = y + z + x; // result == 6
// perform the 'post' operations
y += 1;
z -= 1;
x += 1;
但是,請記住,這必然是編譯器執行評估的嚴格方式。 對於此表達式,結果已明確定義,您將在示例中結束。 在同一個表達式中使用多個遞增/遞減操作時,很容易將未定義的行為合並到您無法從表達式中特別期待的任何內容中。 請參閱為什么這些構造(使用++)未定義的行為? 詳情。
i++
/ i--
是變量的后遞增和遞減...
所以在我們的表達式中,它將采用初始值來解決然后將inc / dec減1。
int x = 2, y = 3, z = 1;
y++ + z-- + x++;
2 + 3 + 1 = 6
您還可以通過while循環實現不同的行為:
#include <iostream>
void main{
int count = 0;
while (count < 5 )
{
std::cout << "counter is: " << count << std::endl
// replace this line with one of the lines below at a time
}
}
考慮的增量以下表達式count
++count // the variable 'count' will grow from 0 to 4
count++ // ditto, weird as it seems; 'count' grows nonetheless
count = ++count // the old 'count' becomes 'count + 1'
count = count++ // endless loop: back to square zero time and time again
同樣,您可以使用帶前綴的do-while循環獲得更多洞察力
count = 0;
do
{
std::cout << ++count << "\n";
} while (count < 5); // prints out 1 to 5
與后綴相對
count = 0;
do
{
std::cout << count++ << "\n";
} while (count < 5); // prints out 0 to 4
Dim i As Integer = 10
Dim b As Integer
Dim c As Integer
Dim d As Integer
b = ++i
c = i + 1
d = b + c
Response.Write("<br/>")
Response.Write("The Value of ++i :-" & b)
Response.Write("<br/>")
Response.Write("The Value of i++ :-" & c)
Response.Write("<br/>")
Response.Write("Answer is " & d)
輸出:
The Value of ++i :-10
The Value of i++ :-11
Answer is 21
這意味着++ var返回原始值,var ++返回遞增值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.