Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views2 pages

CPP Value Vs Reference Defined With Examples

The document explains the differences between pass by value and pass by reference in C++. Pass by value creates a copy of the variable, while pass by reference allows direct access to the original variable. It also discusses when to use each method, highlighting that pass by reference is useful for modifying original data and saving memory, whereas pass by value is safer for protecting original data.

Uploaded by

yonaswelay1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

CPP Value Vs Reference Defined With Examples

The document explains the differences between pass by value and pass by reference in C++. Pass by value creates a copy of the variable, while pass by reference allows direct access to the original variable. It also discusses when to use each method, highlighting that pass by reference is useful for modifying original data and saving memory, whereas pass by value is safer for protecting original data.

Uploaded by

yonaswelay1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Pass by Value vs Pass by Reference in C++

Definition in C++:

1. Pass by Value:

- In pass by value, the function gets a COPY of the original variable.

- Changes made to the parameter inside the function do NOT affect the original variable.

Example:

#include <iostream>

using namespace std;

void change(int num) {

num = 10;

cout << "Inside function: " << num << endl;

int main() {

int x = 5;

change(x);

cout << "Outside function: " << x << endl; // x is still 5

return 0;

2. Pass by Reference:

- In pass by reference, the function gets DIRECT access to the original variable using &.
- Changes made to the parameter inside the function DO affect the original variable.

Example:

#include <iostream>

using namespace std;

void change(int &num) {

num = 10;

cout << "Inside function: " << num << endl;

int main() {

int x = 5;

change(x);

cout << "Outside function: " << x << endl; // x becomes 10

return 0;

Why use Pass by Reference?

- When you want the function to modify the original variable.

- When passing large data like arrays or objects to save memory.

Why use Pass by Value?

- When you only want to read the data.

- When you want to keep the original data safe from being changed.

You might also like