問題描述
以下 for 循環產生相同的結果,即使一個使用后增量,另一個使用預增量.
The following for loops produce identical results even though one uses post increment and the other pre-increment.
代碼如下:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
我為兩個for"循環得到相同的輸出.我錯過了什么嗎?
I get the same output for both 'for' loops. Am I missing something?
推薦答案
i++
或 ++i
求值后,i
在這兩種情況下都是一樣的.前后自增的區別在于對表達式本身的求值結果.
After evaluating i++
or ++i
, the new value of i
will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.
++i
遞增 i
并計算為 i
的新值.
++i
increments i
and evaluates to the new value of i
.
i++
計算為 i
的舊值,并遞增 i
.
i++
evaluates to the old value of i
, and increments i
.
這在 for 循環中無關緊要的原因是控制流的工作方式大致如下:
The reason this doesn't matter in a for loop is that the flow of control works roughly like this:
- 測試條件
- 如果為假,則終止
- 如果為真,則執行正文
- 執行增量步驟
因為(1)和(4)是解耦的,無論是前置還是后置都可以使用.
Because (1) and (4) are decoupled, either pre- or post-increment can be used.
這篇關于“for"循環中的后增量和預增量產生相同的輸出的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!