for循环中的++i和i++有区别吗?这仅仅是语法问题吗?
当前回答
在这两种情况下,'i'将加1。
但是当你在表达式中使用它时,就有区别了,例如:
int i = 1;
int a = ++i;
// i is incremented by one and then assigned to a.
// Both i and a are now 2.
int b = i++;
// i is assigned to b and then incremented by one.
// b is now 2, and i is now 3
其他回答
我不知道其他语言,但在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
下面是一个Java-Sample和字节码,后增量和前增量显示字节码没有区别:
public class PreOrPostIncrement {
static int somethingToIncrement = 0;
public static void main(String[] args) {
final int rounds = 1000;
postIncrement(rounds);
preIncrement(rounds);
}
private static void postIncrement(final int rounds) {
for (int i = 0; i < rounds; i++) {
somethingToIncrement++;
}
}
private static void preIncrement(final int rounds) {
for (int i = 0; i < rounds; ++i) {
++somethingToIncrement;
}
}
}
现在对于字节码(javap -private -c PreOrPostIncrement):
public class PreOrPostIncrement extends java.lang.Object{
static int somethingToIncrement;
static {};
Code:
0: iconst_0
1: putstatic #10; //Field somethingToIncrement:I
4: return
public PreOrPostIncrement();
Code:
0: aload_0
1: invokespecial #15; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: sipush 1000
3: istore_1
4: sipush 1000
7: invokestatic #21; //Method postIncrement:(I)V
10: sipush 1000
13: invokestatic #25; //Method preIncrement:(I)V
16: return
private static void postIncrement(int);
Code:
0: iconst_0
1: istore_1
2: goto 16
5: getstatic #10; //Field somethingToIncrement:I
8: iconst_1
9: iadd
10: putstatic #10; //Field somethingToIncrement:I
13: iinc 1, 1
16: iload_1
17: iload_0
18: if_icmplt 5
21: return
private static void preIncrement(int);
Code:
0: iconst_0
1: istore_1
2: goto 16
5: getstatic #10; //Field somethingToIncrement:I
8: iconst_1
9: iadd
10: putstatic #10; //Field somethingToIncrement:I
13: iinc 1, 1
16: iload_1
17: iload_0
18: if_icmplt 5
21: return
}
问题是:
for循环中的++i和i++有区别吗?
答案是:不。
为什么每个答案都必须详细解释前增量和后增量,而这个问题甚至都没有问过?
这样的循环:
for (int i = 0; // Initialization
i < 5; // Condition
i++) // Increment
{
Output(i);
}
在不使用循环的情况下转换为下面的代码:
int i = 0; // Initialization
loopStart:
if (i < 5) // Condition
{
Output(i);
i++ or ++i; // Increment
goto loopStart;
}
现在你把i++还是++i作为增量有关系吗?不,它不会,因为增量操作的返回值是不重要的。i将在for循环体内的代码执行之后递增。
如果在循环中不使用增量之后的值,则没有区别。
for (int i = 0; i < 4; ++i){
cout<<i;
}
for (int i = 0; i < 4; i++){
cout<<i;
}
这两个循环都输出0123。
但是当你在循环中使用自增/自减后的值时,区别就来了:
预增量循环:
for (int i = 0,k=0; i < 4; k=++i){
cout<<i<<" ";
cout<<k<<" ";
}
输出: 0 0 1 2 - 2 3个3
增量后循环:
for (int i = 0, k=0; i < 4; k=i++){
cout<<i<<" ";
cout<<k<<" ";
}
输出: 0 0 1 0 2 1 3 - 2
我希望通过比较输出可以清楚地看出差异。这里需要注意的是,递增/递减总是在for循环的末尾执行,因此结果可以解释。
正如@Jon B所说,在for循环中没有区别。
但在一段时间或做…While循环,如果你与++i或i++进行比较,你会发现一些不同
while(i++ < 10) { ... } //compare then increment
while(++i < 10) { ... } //increment then compare