0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

インクリメント演算子の前置と後置について

Posted at

インクリメント演算子の前置と後置の違い

javaシルバーの資格勉強をしていた際、インクリメント演算子が前と後ろに置かれているものがあり、「どっちだったかな〜」とど忘れしたので、その備忘録として。

前置のインクリメント

++i

このようなもの。

後置のインクリメント

i++

このようなもの

どう違うのか

簡単にいってしまうと、評価されるタイミングが違う。

前置インクリメントの例

int num=0;

System.out.println(++num);      

//1が表示される

先にnum=0にプラス1してから(評価してから)表示させている。

続いて後置インクリメントの例

int num=0;

System.out.println(num++);  //0が表示

System.out.println(num);  //1が表示

1回目のSysoutでは後置インクリメントなので、一旦変数numの値を表示してから、プラス1をしている。
2回目のSysoutでは、1回目でプラス1した値(変数num=1)を表示している 

最後に

なんだかんだ忘れやすい(自分だけかも)ので自分自身の戒めとして記録しました。以上備忘録でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?