Example of Pass by Reference
In the below program, the arguments that are passed by reference will be swapped with each other.
C
// C program to swap two numbers #include <stdio.h> // function definition with relevant pointers to recieve the // parameters void swap( int * a, int * b) { // accessing arguments like pointers int temp = *a; *a = *b; *b = temp; } // driver code int main( void ) { int n1 = 5; int n2 = 10; // value before swapping printf ( " Before swapping : n1 is %d and n2 is %d\n" , n1, n2); // calling the function by passing the address of the // arguments swap(&n1, &n2); // value after swapping printf ( " After swapping : n1 is %d and n2 is %d\n" , n1, n2); return 0; } |
Before swapping : n1 is 5 and n2 is 10 After swapping : n1 is 10 and n2 is 5
Explanation
In the above code, n1 and n2 are assigned by the values 5 and 10. When the swap function is called and the address of n1, and n2 are passed as a parameter to the function, then the changes made to the n1 and n2 in the swap function will also reflect in the main function. The swap function will directly access and change the values of n1, and n2 using their addresses. So, after execution of the swap function, the values of n1 and n2 are swapped.
Pass By Reference In C
Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program.
Contact Us