LoginSignup
1
1

More than 5 years have passed since last update.

a++ & ++aの違い = 前置インクリメントと後置インクリメントに違い

Last updated at Posted at 2015-11-03
Which choice is the output value of the following code:
var a = 0
let b = ++a
let c = a++
print("\(a)  \(b)  \(c)") //211

注釈

If the operator appears before the variable, it increments the variable before returning its value.

もしオペレータが変数の前に表示される場合は、オペレーターが値を戻す前に、その変数をインクリメント(加算)します。

If the operator appears after the variable, it increments the variable after returning its value.

もしオペレータが変数の後に表示される場合は、オペレーターが値を戻した後、その変数をインクリメント(加算)します。

インクリメントとは

インクリメント = 変数の値を「1」増やす処理の事を表す。
この時、前置と後置の明確な違いは、「処理(計算)順序」が変わる事にある。
前置の場合はほかの演算よりも先に変数の値を1増加させる処理を行う。
++a => aを1つ増やしてから、その結果を式の値として返す
後置の場合はほかの演算よりも後に変数の値を1増加させる処理を行う。
a++ => aの値を返した後に、aを一つ増やす。

コードで表すと下記のようになる。

var a = 0
let b = ++a
let c = a++
print("\(a)  \(b)  \(c)")


//インクリメントを使用しないで、記述する場合

var a = 0

//let b = ++a
//aの値を一つ増やしてから、その結果を式の値として返す。
a = a + 1
let b = a 

//let c = a++
//aの値を返した後に、aの値を一つ増やす。
let c = a
a = a + 1

print("\(a) \(b) \(c)")

練習

インクリメントを使わずに、一つ一つの計算結果を理解しておく。

var a = 5

//let b = ++a + 5

a = a + 1 
let b = a + 5

//let c = a++ + 5
let c = a + 5
a = a + 1

print("\(a) \(b) \(c)")

答え

// 7 11 11

参照
https://programmer-engine.work/archives/16831
http://ai-future.hatenablog.jp/entry/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9E%E3%83%BC%E6%9C%AA%E7%B5%8C%E9%A8%93%E3%81%8D%E3%81%A4%E3%81%84

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