Call by value and Call by reference in c++

C++ programming में function को value या data पास करने के दो तरीके हैं: Call by Value और Call by reference। Call by value में original value को modified नहीं किया जाता है, लेकिन call by reference, original वैल्यू को modified किया जाता है।

Call by value in C++ :

Call by value में, original value को modified नहीं किया जाता है।

call by value में, function को पास की जा रही value स्थानीय रूप से स्टैक मेमोरी लोकेशन में फ़ंक्शन पैरामीटर द्वारा संग्रहीत किया जाता है। यदि आप function parameter की value change करते  हैं, तो यह केवल present function के लिए बदल जाता है। यह calling method के अंदर variable के value को नहीं बदलेगा जैसे कि main function().

#inclue<iostream>
using namespace std;
void change(int data);
int main(){
   int data = 3;
   change (data);
   cout << "value of data is :" << data<< endl;
   return 0;
}
void change (int data)
{
data = 5;
}

Output :

value of data is : 3

Call by reference :

Call by reference में, original value modified किया जाता  है क्योंकि हम reference (address) pass करते हैं। यहां value का address, function में passed किया जाता है, इसलिए actual और formal arguments same address space को  share करते हैं। इसलिए, function के अंदर changed value, function के अंदर और साथ ही बाहर reflect होता है।

Note: Call by reference को समझने के लिए, आपको Pointers का basic knowledge होना चाहिए।

Let’s try to understand call by reference by given example –

#include<iostream>
using namespace std;
void swap(int*x,int*y){
int swap;
swap = *x;
*x = *y;
*y = swap;
}
int main(){
int x = 400, y = 500;
swap(&x,&y); // here we are calling the function
cout<< "value of x is :"<<x <<endl;
cout<< "value of y is :"<<y <<endl;
return 0;
}

Output :

value of x is : 500
value of y is :400

 

Difference between call by value and call by reference :

Call by value Call by reference
Function को value की copy pass की जाती है Function को value की address pass की जाती है

Function के अंदर किए गए changes अन्य functions को reflect नहीं करते  हैं

Function के अंदर किए गए changes अन्य functions को reflect  करते  हैं

 Actual और formal argument create, Different memory locations में किये जाते है ।

 Actual और formal argument, same memory locations में create किये जाते है ।
Previous articleLoops in C
Next articleRecursion in C ++

LEAVE A REPLY

Please enter your comment!
Please enter your name here