Pass by Value Vs Ref
Pass by Value Vs Ref
Pass by Value:
Definition: When a function is called, a copy of the actual argument is passed to the
function.
Effect: Changes made to the parameter inside the function do not affect the original
argument.
Use Case: Primarily used for primitive data types like int, float, etc.
Example:
void function(int x) {
x = 10; // Changes only local copy
}
int a = 5;
function(a);
// 'a' remains 5 after function call
Pass by Reference:
Definition: When a function is called, a reference (or address) to the actual argument is
passed, allowing the function to modify the original variable.
Effect: Changes made to the parameter inside the function will affect the original
argument.
Use Case: Commonly used for larger data structures (like arrays or objects) to avoid
copying, and to modify the original argument.
Example:
void function(int &x) {
x = 10; // Modifies the original variable
}
int a = 5;
function(a);
// 'a' becomes 10 after function call
Summary:
Pass by Value: Creates a copy of the argument; no effect on the original variable.
Pass by Reference: Passes the address of the argument; changes affect the original
variable.