变量自增的陷阱

来源:互联网 发布:休闲单机游戏推荐知乎 编辑:程序博客网 时间:2024/05/22 02:22

有如下代码

public void test(){    int count = 1;    count = count++;    System.out.println("count的值为->"+count);}

输出结果为:count的值为1

原理:

 count++细分为三个步骤:     int temp = count;     temp = temp+1;     //相关操作之后     count = temp; 因此count = count++细分为:     int temp = count;     temp = temp+1;     count = count;

而第二种形式:

public void test2(){    int count = 1;    count = ++count;    System.out.println("count的值为->"+count);    //输出的结果为:  count的值为->2  }