for循环中的++i和i++有区别吗?这仅仅是语法问题吗?
当前回答
正如@Jon B所说,在for循环中没有区别。
但在一段时间或做…While循环,如果你与++i或i++进行比较,你会发现一些不同
while(i++ < 10) { ... } //compare then increment
while(++i < 10) { ... } //increment then compare
其他回答
一个(++i)是前增量,一个(i++)是后增量。区别在于表达式立即返回什么值。
// Psuedocode
int i = 0;
print i++; // Prints 0
print i; // Prints 1
int j = 0;
print ++j; // Prints 1
print j; // Prints 1
编辑:哎呀,完全忽略了循环方面的事情。在for循环中,当它是'step'部分(for(…;…。)),但它也可以在其他情况下发挥作用。
在c#中,在for循环中使用没有区别。
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
输出和
for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }
正如其他人指出的那样,在一般情况下i++和++i有一个微妙但显著的区别:
int i = 0;
Console.WriteLine(i++); // Prints 0
int j = 0;
Console.WriteLine(++j); // Prints 1
i++读取I的值,然后增加它。
++i增加i的值,然后读取它。
对于循环可能会有不同。这是后增量/前增量的实际应用。
int i = 0;
while(i++ <= 10) {
Console.Write(i);
}
Console.Write(System.Environment.NewLine);
i = 0;
while(++i <= 10) {
Console.Write(i);
}
Console.ReadLine();
虽然第一个数到11,循环11次,但第二个不是。
这通常用于简单的while(x——> 0);- -循环迭代数组中的所有元素(这里不包括foreach-construct)。
我不知道其他语言,但在java++中,I是一个前缀增量,这意味着:将I增加1,然后在I所在的表达式中使用I的新值,i++是一个后缀增量,这意味着:在表达式中使用I的当前值,然后将其增加1。 例子:
public static void main(String [] args){
int a = 3;
int b = 5;
System.out.println(++a);
System.out.println(b++);
System.out.println(b);
} 输出为:
4 5 6
关于++i和i++,不仅仅是循环和性能差异。++i返回一个l值,i++返回一个r值。基于此,可以对(++i)执行许多操作,但不能对(i++)执行许多操作。
1- It is illegal to take the address of post increment result. Compiler won't even allow you.
2- Only constant references to post increment can exist, i.e., of the form const T&.
3- You cannot apply another post increment or decrement to the result of i++, i.e., there is no such thing as I++++. This would be parsed as ( i ++ ) ++ which is illegal.
4- When overloading pre-/post-increment and decrement operators, programmers are encouraged to define post- increment/decrement operators like:
T& operator ++ ( )
{
// logical increment
return *this;
}
const T operator ++ ( int )
{
T temp( *this );
++*this;
return temp;
}
推荐文章
- 如何在for循环中注释类型?
- 在支持循环和函数的语言中,是否存在“goto”的合法用例?
- 为什么不使用异常作为常规的控制流呢?
- 列表推导式和函数式函数比for循环更快吗?
- 什么是序列化?
- 我怎么能循环通过一个列表<T>和抓取每个项目?
- 每个递归都可以转换成迭代吗?
- 去下一次迭代在java For循环
- 什么是ORM,它是如何工作的,我应该如何使用它?
- 我能在服务器端应用程序(PHP、Ruby、Python等)上读取URL的哈希部分吗?
- 元素在“for(…in…)”循环中排序
- 多少个参数是太多?
- 是否有可能在没有迭代器变量的情况下实现Python for range循环?
- 对于不可变集合上的非突变“add”方法,最好的名称是什么?
- foo到底是什么意思?