What exactly does “pass by reference” mean?

后端 未结 8 2153
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 03:15

And who has the authority to decide?

Edit: Apparently I haven\'t succeeded in formulating my question well.
I am not asking how Java\'s

8条回答
  •  自闭症患者
    2020-12-30 04:20

    Both of your C examples actually demonstrate pass-by-value, because C doesn't have pass-by-reference. It's just that the value that you're passing is a pointer. Pass-by-reference occurs in languages such as Perl:

    sub set_to_one($)
    {
        $_[0] = 1; # set argument = 1
    }
    my $a = 0;
    set_to_one($a); # equivalent to: $a = 1
    

    Here, the variable $a is actually passed by reference, so the subroutine can modify it. It's not modifying some object that $a is pointing to via indirection; rather, it modifies $a itself.

    Java is like C in this respect, except that in Java objects are "reference types", so all you ever have (and all you can ever pass) are pointers to them. Something like this:

    void setToOne(Integer i)
    {
        i = 1; // set argument = 1
    }
    
    void foo()
    {
        Integer a = 0;
        setToOne(a); // has no effect
    }
    

    won't actually change a; it only reassigns i.

提交回复
热议问题