不同之处在于后增量和前增量,在代码运行时始终相同。

huangapple go评论65阅读模式
英文:

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 &lt;= 10; ++i) {
		System.out.println(tableOf * i);
		System.out.println(i);
        }
		int tableof = 4;
		for (int y = 1; y &lt;= 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++; -&gt; c = 3

or

int c = a + ++b; -&gt; c = 4

huangapple
  • 本文由 发表于 2020年10月10日 22:44:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64294653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定