Advertisement

Difference between Call by Value and Call by Reference Functions in C Programming

 

Difference between Call by Value and Call by Reference Functions in C Programming

Difference between Call by Value and Call by Reference Functions in C Programming

The parameters of functions can be passed in two ways:
1. Call by value: A copy of the variable is passed to the function.
2. Call by reference: An address of the variable is passed to the function.

a) The C program for Call by Value:-

#include<stdio.h> void swap(int n1, int n2) { int temp = n1; n1 = n2; n2 = temp; printf("The numbers after swapping n1 and n2 in swap function is %d %d \n",n1, n2); } int main() { int x = 20; int y = 68; printf("The numbers before swapping n1 and n2 %d %d \n",x, y); swap(x, y); printf("The numbers after swapping n1 and n2 in main function is %d %d \n",x, y); return 0; }

Output:-
The numbers before swapping n1 and n2 20 68 The numbers after swapping n1 and n2 in swap function is 68 20 The numbers after swapping n1 and n2 in main function is 20 68

In the example above, we are simply swapping two numbers but swapping took place inside the swap function, but not in the main function because we have sent a copy of the variable instead of its exact address.

b) The C program for Call by Address:-

#include<stdio.h> void swap(int *n1 ,int *n2) { int temp = *n1; *n1 = *n2; *n2 = temp; } int main() { int n1 = 20; int n2 = 68; printf("The numbers before swapping n1 and n2 %d %d \n",n1, n2); swap(&n1, &n2); printf("The numbers after swapping n1 and n2 %d %d",n1, n2); return 0; }

Output:-
The numbers before swapping n1 and n2 20 68 The numbers after swapping n1 and n2 68 20

In this above example, the output shows the correct result. This happens because we have sent the actual address of the variables.

Post a Comment

0 Comments