Answer to Question #157626 in C++ for zain ul abdeen

Question #157626

What is the difference between pass by value and pass by reference? Explain using an example.



1
Expert's answer
2021-01-26T08:11:22-0500

It's a way how to pass arguments to functions. Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself). Pass by value means the called functions' parameter will be a copy of the callers' passed argument. The value will be the same, but the identity - the variable - is different. Thus changes to a parameter done by the called function in one case changes the argument passed and in the other case just changes the value of the parameter in the called function (which is only a copy). In a quick hurry:



C++ supports pass by value and pass by reference (reference parameter type used at called function).


// passes a pointer (called reference in java) to an integer
void call_by_value(int *p) { // :1
p = NULL;
}

// passes an integer
void call_by_value(int p) { // :2
p = 42;
}

// passes an integer by reference
void call_by_reference(int & p) { // :3
p = 42;
}

// this is the java style of passing references. NULL is called "null" there.
void call_by_value_special(int *p) { // :4
*p = 10; // changes what p points to ("what p references" in java)
// only changes the value of the parameter, but *not* of
// the argument passed by the caller. thus it's pass-by-value:
p = NULL;
}

int main() {
int value = 10;
int * pointer = &value;

call_by_value(pointer); // :1
assert(pointer == &value); // pointer was copied

call_by_value(value); // :2
assert(value == 10); // value was copied

call_by_reference(value); // :3
assert(value == 42); // value was passed by reference

call_by_value_special(pointer); // :4
// pointer was copied but what pointer references was changed.
assert(value == 10 && pointer == &value);
}
And an example in Java won't hurt:

class Example {
int value = 0;

// similar to :4 case in the c++ example
static void accept_reference(Example e) { // :1
e.value++; // will change the referenced object
e = null; // will only change the parameter
}

// similar to the :2 case in the c++ example
static void accept_primitive(int v) { // :2
v++; // will only change the parameter
}

public static void main(String... args) {
int value = 0;
Example ref = new Example(); // reference

// note what we pass is the reference, not the object. we can't
// pass objects. The reference is copied (pass-by-value).
accept_reference(ref); // :1
assert ref != null && ref.value == 1;

// the primitive int variable is copied
accept_primitive(value); // :2
assert value == 0;
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS