Monday, November 27, 2017

Call by Value, Call by Reference and Call by Pointer

#include <iostream>
using namespace std;

void call_by_reference_swap(int& x, int& y) {
int temp;
temp = x;
x = y;
y = temp;
}

void call_by_pointer_swap(int* x, int* y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}

void call_by_value_swap(int x, int y) {
int temp;
temp = x;
x = y;
y = temp;
}

int main() {
int a = 10, b = 20;
cout << "a = " << a << "\t b = " << b << endl;

call_by_value_swap (a, b);
cout << "a = " << a << "\t b = " << b << endl;  // Expected output a = 10, b = 20

call_by_reference_swap(a, b);
cout << "a = " << a << "\t b = " << b << endl;  // Expected output a = 20, b = 10

call_by_pointer_swap(&a, &b);
cout << "a = " << a << "\t b = " << b << endl;  // Expected output a = 10, b = 20

return 0;
}

------------------
Output:
------------------
a = 10   b = 20
a = 10   b = 20
a = 20   b = 10
a = 10   b = 20
Press any key to continue . . .

References always pointing to "something" as compared to "pointers"  which can point to anything. 

Example
void call_by_pointer_swap(int* x, int* y) {
int temp;
temp = *x;
x++;
*x = *y; 
*y = temp;

}

Now this code can behave haywire or even crash. You can't say. That's why from safe programming aspect, its good practice "when in doubt, go for call by reference" :)

No comments:

Post a Comment

PROFILE

My photo
India
Design Engineer ( IFM Engineering Private Limited )

Followers