LoginSignup
7
6

More than 5 years have passed since last update.

インクリメントリターン

Last updated at Posted at 2014-04-12

Java小ネタ。

後置インクリメントは値の評価後に加算処理が行われるのはおなじみですよね。
で、こんな感じで関数のreturnでインクリメントしたらどうなるのだろうと。

public class Foo {

    private static int x = 0;
    public static void main(String[] args) {
        System.out.println(countUp()); // -> 0
        System.out.println(countUp()); // -> 1
    }

    private static int countUp() {
        return x++;
    }
}

加算前の値をreturnした後に、加算処理が行われているようです。良かったです。
・・・returnした後に、加算処理?

なんでこんな芸当が出来るのかよくわからなくなったので、マシン語翻訳。countUpの部分です。

  private static int countUp();
     0  getstatic Foo.x : int [10]
     3  dup
     4  iconst_1
     5  iadd
     6  putstatic Foo.x : int [10]
     9  ireturn
      Line numbers:
        [pc: 0, line: 11]

変数を複製して、スタティックフィールド(x)に反映する値と、returnで戻す値を別々に用意しているようです。なるほど。

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