Docsity

Call by Value vs Call by Reference in C++: Complete Conceptual Guide, Lecture notes of Computer Science

Toggle sidebar
bg1
1. Introduction
In C++, when we pass arguments to a function, there are two primary methods used to handle the
memory data: Call by Value and Call by Reference.
2. Call by Value
In this method, a copy of the actual argument's value is passed to the function's parameters.
Any changes made to the parameters inside the function do not affect the original
variables in the main() function.
💻 Solved Example:
C++
#include <iostream>
using namespace std;
void modifyValue(int num) {
num = num + 10; // Changes only the copy
}
int main() {
int x = 5;
modifyValue(x);
cout << "Value of x: " << x << endl; // Output remains 5
return 0;
}
3. Call by Reference
In this method, the address (reference) of the actual argument is passed using the ampersand (&)
operator.
Any changes made to the parameters inside the function directly modify the original
variables in the main() function.
pf2

Partial preview of the text

Download Call by Value vs Call by Reference in C++: Complete Conceptual Guide and more Lecture notes Computer Science in PDF only on Docsity!

1. Introduction

In C++, when we pass arguments to a function, there are two primary methods used to handle the

memory data: Call by Value and Call by Reference.

2. Call by Value

In this method, a copy of the actual argument's value is passed to the function's parameters.

 Any changes made to the parameters inside the function do not affect the original

variables in the main() function.

💻 Solved Example:

C++

#include using namespace std; void modifyValue(int num) { num = num + 10 ; // Changes only the copy } int main() { int x = 5 ; modifyValue(x); cout << "Value of x: " << x << endl; // Output remains 5 return 0 ; }

3. Call by Reference

In this method, the address (reference) of the actual argument is passed using the ampersand (&)

operator.

 Any changes made to the parameters inside the function directly modify the original

variables in the main() function.

💻 Solved Example:

C++

#include using namespace std; void modifyReference(int &num) { num = num + 10 ; // Directly changes the original variable } int main() { int x = 5 ; modifyReference(x); cout << "Value of x: " << x << endl; // Output becomes 15 return 0 ; }

4. Quick Comparison Table

Feature Call by Value Call by Reference

Arguments

Passed

Copy of the actual data

value.

Reference/Memory address of

data.

Original Variable

Remains completely

unchanged.

Gets modified if parameter

changes.

Memory

Efficiency

Low (Creates extra copies).

High (Uses the same memory

space).

Syntax Pointer Standard variable (int num). Ampersand variable (int &num).