How to swap two numbers using call by reference in C , C++. In the interviews interviewer generally asked the difference between call by reference and call by value. In this post let’s understand what is call by reference and how to swap two numbers using call by reference method.
In Call By Reference method, we pass the address(reference/pointer) of an object instead of it’s value.It means the changes made to the parameter affect the passed argument. By using call by reference method no additional memory is used as we are using pointers. .To pass an address we use (&) ampresand operator.
C , C++ Programming MCQ for practice.
To declare a pointer in C asterisk(*) operator is used.
1 2 3 |
int *firstnum; // firstnum is a pointer of int type. swap (&a,&b); // Passing address of a and b. |
Swap two numbers using third variable .
Swap two numbers without using third variable .
Swap two numbers using XOR operator .
Program to Swap Two Numbers using Call by Reference
Let’s write a program to swap two numbers using call by reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h> /* Function to swap numbers. */ void swap(int *firstnum, int *secondnum){ int temp; temp = *firstnum; *firstnum = *secondnum; *secondnum = temp; } main() { int a=12,b=13; /* Pass address of a and b variable. */ swap(&a,&b); printf("Values of a and b is %d %d",a,b); } |
Important Points
i) In this program i use swap function to swap two numbers.
ii) In case of call by reference method, i have not return anything from swap function. As the variables are referencing memory. If i used call by value method in that case i need to return the firstnum and secondnum variable values.