Sunday, 3 August 2025

Difference between call by value and call by reference

 

Aspect

Call by Value

Call by Reference

Definition

In Call by Value, a copy of the actual value is passed to the function. Changes made inside the function do not affect the original variable.

In Call by Reference, the reference (memory address) of the original variable is passed. Changes inside the function directly affect the original variable.

Data Passed

Only the value of the variable is passed.

The address (reference) of the variable is passed.

Effect on Original Variable

Original data remains unchanged, as the function works on a copy.

Original data can be modified, as the function works on the actual data.

Memory Usage

Requires more memory, since copies are created.

Uses less memory, as it avoids duplication by using references.

Performance

Slightly slower if large data structures are passed (due to copying).

Generally faster for large data structures as only addresses are passed.

Function Behavior

Safe approach; function cannot accidentally modify the caller’s data.

Riskier; the function can unintentionally alter the caller’s variables.

Use Case

Useful when you want to protect original data and avoid side effects.

Ideal when you want the function to modify the original variable or handle large objects.

Example Languages

Supported in C, Java (primitive types), Python (for immutable objects).

Used in C++, Python (mutable types), and C with pointers.

Syntax (C/C++)

void func(int x) { x = 10; }func(a); // a remains unchanged

void func(int &x) { x = 10; }func(a); // a is modified

Security

More secure due to isolation of data between function and caller.

Less secure, especially in large projects, as changes can propagate unexpectedly.

Side Effects

No side effects – the function doesn’t alter the input variables.

Has side effects – input variables can be directly changed.

Real-World Analogy

Giving someone a photocopy of a document – they can write on it, but the original stays safe.

Giving someone the original document – any changes made will directly affect it.

 

No comments:

Post a Comment