DenkzeitWiki

Suchen:

Aktuelle Änderungen Printable View Änderungen Bearbeiten

BurroughsB5000 > BusinessRules > C > CLanguage > CASE > ComputerAidedSoftwareEngineering > CLOS > CommonLispObjectSystem > CLR > CommonLanguageRuntime > CLanguage > CPlusPlus > CPlusPlusSprache > CS > ComputerScience > CVS > CallByReferenceOrValueClear Trail
Main /

Call By Reference Or Value


Call-by-value(CBV) copies the data or object given to a function (method). CBV is expensive for big mutable objects.
Call-by-reference(CBR) gives a reference to the object to a function (method).


Typically, a reference is the memory address at which the object or array is stored. However, since Java references are opaque and cannot be manipulated in any way, this is an implementation detail. [1]



Examples


in C/C++

CPlusPlus
 void f( int x ){
   x = x * 2;
 }
x does not change for the caller.
 void g( int& x ){
   x = x * 2;
 }
x changes for the caller. Using a reference (as & implies) changes to the referenced object are reflected outside of the function that does the changes.
 void h( int* x ){
   (*x) = (*x) * 2;
 }
Pointers work the same as references (here), are a bit more uncomfortable to use than references, though.

in Java

Java
 void f( int x ){
   x = x * 2;
 }
x does not change for the caller.
 void g( SomeObject x ){
   x = new SomeObject()
 }
The Object that is referenced by x does not change for the caller. Assigning a new value to x changes the local reference but not the reference at the caller's site. That's because Java always passes parameter by value. If the parameter is an object (which Java always referrs to via references) the reference to the object is passed by value, which results in a copy of the reference.
 void h( SomeObject x ){
   x.doSomethingWithSideEffect()
 }
Here x is changed and these changes are visible to the caller of h. x is a reference, pointing to some object. Invoking a method on that object (via the reference) changes the object (if the method has sideeffects).
 void i( SomeObject x ){
   x = new SomeObject()
   x.doSomethingWithSideEffect()
 }
Since before invoking a method on the object, the reference is in effect redirected, no changes are visible to the caller, again.

in Python

Python In Python all variables are in effect references to objects. Even for primitive types like integers.
Python also uses call-by-value on these references, which results in Java-like behavior:
 >>> def f(x):
 ...     x = x * 2
 ...
 >>> s = 5
 >>> l = ['o']
 >>> f(s), f(l)
 (None, None)
 >>> s
 5
 >>> f(s)
 >>> s
 5
 >>> f(l)
 >>> l
 ['o']

 >>> def g(x):
 ...     x.append('la')
 ...
 >>> g(l)
 >>> l
 ['o', 'la']
Note the beauty of an interactive interpreter. I think Python very much boosts learning by providing this kind of interactivity: instant feedback.

Edit - BackLinks - Tags - Page Hist - Print - Changes - Home - Orphans - Help

Zuletzt geändert am 13.01.2006 18:02 Uhr und seit 7. April 2005 2701 aufgerufen.