In this article we will learn to implement a C program to demonstrate call by value and call by reference. A C program is provided below to illustrate how to use call by value and call by reference parameter passing mechanisms in case of functions.
Program is as follows:
/*
* C program to demonstrate call by value and call by reference
* Author: P.S.SuryaTeja
*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
void swapval(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
void swapref(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main(int argc, char **argv)
{
int num1, num2;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
swapval(num1, num2);
printf("\nAfter swapping using call by value, num1 = %d and num2 = %d", num1, num2);
swapref(&num1, &num2);
printf("\nAfter swapping using call by reference, num1 = %d and num2 = %d", num1, num2);
getch();
return 0;
}
Input and output for the above program is as follows:
Enter two numbers: 20 50
After swapping using call by value, num1 = 20 and num2 = 50
After swapping using call by reference, num1 = 50 and num2 = 20
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply