1
0

More than 3 years have passed since last update.

インクリメント演算子、デクリメント演算子

Posted at

単体ではさほど難しくはないけど、束になってかかってくるとややこしいのでまとめです。

インクリメント演算子、デクリメント演算子とは

  • インクリメント「++」・・・変数の値に1を加算する
  • デクリメント「--」・・・変数の値に1を減算する

前置と後置

前置・・・先に演算してその結果の値を代入する

int a = 5
int b = ++a

↑aに1を加算してからbに代入(b=6、a=6)

後置・・・値を代入してからあとで演算する

int a = 5
int b = a++

↑bに代入してからaに1を加算(b=5、a=6)

ややこしい計算の例

int a=5
int b = a++ + ++a + --a - a-- -a

とかやると
b = 5 + 7 + 6 - 6 - 5

となり、答えは7

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