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

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

difference between post and pre increment, the code running is always same

问题

我想知道后增和前增的区别,基本上,我将两个相同的代码一起写,只需更改变量以检查后增和前增是否有任何区别。但是结果是相同的?

  1. int tableOf = 4;
  2. for (int i = 1; i <= 10; ++i) {
  3. System.out.println(tableOf * i);
  4. System.out.println(i);
  5. }
  6. int tableof = 4;
  7. for (int y = 1; y <= 10; y++) {
  8. System.out.println(tableof * y);
  9. System.out.println(y);
  10. }
英文:

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??

  1. int tableOf = 4;
  2. for (int i = 1; i &lt;= 10; ++i) {
  3. System.out.println(tableOf * i);
  4. System.out.println(i);
  5. }
  6. int tableof = 4;
  7. for (int y = 1; y &lt;= 10; y++) {
  8. System.out.println(tableof * y);
  9. System.out.println(y);
  10. }

答案1

得分: 1

后增量使用值并在使用后对其进行递增。前增量会先递增值,然后再使用它。
在for循环的示例中,过程如下:

  1. i = i++;

或者

  1. i = ++i;

在这种情况下,无论是使用前增量还是后增量,最终i都会增加1。

一个相关的例子是加法:

  1. int a = 1;
  2. int b = 2;
  3. int c = a + b++; // c = 3

或者

  1. 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

  1. i = i++;

or

  1. 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:

  1. int a = 1;
  2. int b = 2;
  3. int c = a + b++; -&gt; c = 3

or

  1. 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:

确定