循环中的前增量和后增量之间的区别? [英] Difference between pre-increment and post-increment in a loop?
本文介绍了循环中的前增量和后增量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for
循环中的++i
和i++
是否存在差异?仅仅是语法吗?
Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
推荐答案
a ++被称为后缀.
向a加1,返回旧值.
++ a被称为前缀.
向a加1,返回新值.
C#:
string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
Console.WriteLine(++i);
}
Console.WriteLine("");
i = 0;
foreach (string item in items)
{
Console.WriteLine(i++);
}
输出:
1
2
3
4
0
1
2
3
foreach
和while
循环取决于您使用哪种增量类型.像下面这样的for循环,因为您没有使用i的返回值,所以没有区别:
foreach
and while
loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:
for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
如果使用评估值,则增量类型将变得很重要:
If the value as evaluated is used then the type of increment becomes significant:
int n = 0;
for (int i = 0; n < 5; n = i++) { }
这篇关于循环中的前增量和后增量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文