LoginSignup
121
37

More than 3 years have passed since last update.

i++と++iの違い

Last updated at Posted at 2018-10-31

概要

前置インクリメント演算子(++i)と後置インクリメント演算子(i++)はどちらもiにi+1の結果を代入する演算子ですが、その違いについてざっくりと説明します。

前置インクリメント(++i)

式の値としてインクリメント後、つまりi+1の値を返します。

i = 1;
j = ++i; // jは2

後置インクリメント(i++)

式の値としてインクリメント前、つまりiの値を返します。

i = 1;
j = i++; // jは1

補足

for (int i = 0; i < n; ++i)
for (int i = 0; i < n; i++)

どちらもよく見るforループですが、このように++i, i++が単独で現れ、式の値を使わない場合は動作に関して違いはありません。
また最近のコンパイラでは最適化によって実行速度にも違いがないため、好みの方を使えばいいと思います。

121
37
21

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
121
37