Swapping values using pointer:
Swapping of values of variables by using pointers is a great example of calling functions by call by reference.
Functions can be called in two ways:
- Call by Value
- Call by reference
In call by value, a copy of actual arguments is passed to formal arguments of the called function. Any change made to the formal arguments in the called function has no effect on the values of actual arguments in the calling function.
In call by reference method, the address of the actual parameter is passed into the formal parameter. Inside the function, the address is used to access the actual argument. Any changes made to the formal parameters are also made to the actual parameters, since the changes are being made to the same location in memory.
We can use pointers to call functions using the call by reference method.
Let us understand how that can be done with this code snippet:
#include <stdio.h> void swap(int *n1, int *n2); int main() { int num1 = 5, num2 = 10; int *ptr1 = &num1; int *ptr2 = &num2; // address of num1 and num2 is passed to the swap function through pointers ptr1 and ptr2 printf("Before swapping \n"); printf("Number1 = %d\n", num1); printf("Number2 = %d\n", num2); swap( ptr1, ptr2); printf("After swapping \n"); printf("Number1 = %d\n", num1); printf("Number2 = %d", num2); return 0; } void swap(int * n1, int * n2) { // pointers n1 and n2 points to the address of num1 and num2 respectively int temp; temp = *n1; *n1 = *n2; *n2 = temp; }
- We are creating two int type varibles num1and num2
- We are passing the address of num1 and num2to the swap function using pointers ptr1 and Therefore, we are sending the address of num1 and num2 to the swap function.
- In the swap function, the values at the addresses of num1and num2 are getting swapped.
Let us look at the output of the above code:
Before swapping Number1 = 5 Number2 = 10 After swapping Number1 = 10 Number2 = 5
The changes are made to the locations in memory and therefore the value of actual parameters are swapped when the values of formal parameters are swapped.
Pictorial representation of the above code:
Report Error/ Suggestion