关于 i++ 和 ++i ,以及在函数中使用 ++ 的重要思考

关于i++和++i的重要思考

先看下面这个程序:

public class PPTest {
    
    
    public static void main(String[] args) {
    
    
        int x=0;
        System.out.println("函数外x为:"+x);
        test(x++);
        System.out.println("现在x是:"+x);
        test(++x);
        System.out.println("现在x是:"+x);
    }

    public static void test(int x) {
    
    
        System.out.println("函数内x为:"+x);
    }
}

image-20210317174231290

看出问题了吗?

没错,函数中,参数调用++,那外部数据也会变化

而且,如果是后++,那么内部函数,调用的是++前的值!

这样的问题,在写回溯相关的问题的时候,会产生重大的影响!!!!



如果要在函数里加,必须写成i+1的形式

public class PPTest {
    
    
    public static void main(String[] args) {
    
    
        int x=0;
        System.out.println("函数外x为:"+x);
        test(x+1);
        System.out.println("现在x是:"+x);
    }

    public static void test(int x) {
    
    
        System.out.println("函数内x为:"+x);
    }
}

image-20210317174601579

md,没想到这个时候还会被++的问题困扰

猜你喜欢

转载自blog.csdn.net/weixin_44062380/article/details/114941036