英文:
difference between post and pre increment, the code running is always same
问题
我想知道后增和前增的区别,基本上,我将两个相同的代码一起写,只需更改变量以检查后增和前增是否有任何区别。但是结果是相同的?
int tableOf = 4;
for (int i = 1; i <= 10; ++i) {
System.out.println(tableOf * i);
System.out.println(i);
}
int tableof = 4;
for (int y = 1; y <= 10; y++) {
System.out.println(tableof * y);
System.out.println(y);
}
英文:
I want to know the difference between post-increment and pre-increment, basically, I wrote two same codes together by just changing the variables to check whether there is any difference in post and pre-increment. but it's the same??
int tableOf = 4;
for (int i = 1; i <= 10; ++i) {
System.out.println(tableOf * i);
System.out.println(i);
}
int tableof = 4;
for (int y = 1; y <= 10; y++) {
System.out.println(tableof * y);
System.out.println(y);
}
答案1
得分: 1
后增量使用值并在使用后对其进行递增。前增量会先递增值,然后再使用它。
在for循环的示例中,过程如下:
i = i++;
或者
i = ++i;
在这种情况下,无论是使用前增量还是后增量,最终i都会增加1。
一个相关的例子是加法:
int a = 1;
int b = 2;
int c = a + b++; // c = 3
或者
int c = a + ++b; // c = 4
英文:
post-increment uses the value and increments it after usage. pre-increment first increments and then uses the value.
in the example of a for-loop the procedure is
i = i++;
or
i = ++i;
in this case it doesnt matter if you are using pre or post in the end i is incremented by 1.
An relevant example would be an addition:
int a = 1;
int b = 2;
int c = a + b++; -> c = 3
or
int c = a + ++b; -> c = 4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论