C Program to demonstrate Pass by Value. Pass by value is a way to pass a variable to a function. The variable is passed by value, not by reference. This means that the function does not have access to the variable’s memory address. The function can only access the variable’s value.
It is the opposite of pass by reference, where the function has access to the variable’s memory address and can modify the variable’s value.
In the case of pass by value, the space allocated for the variable is copied to the function’s memory space. This means that the function can modify the variable’s value without affecting the variable’s memory address.
However in the case of pass by reference, the function can modify the variable’s memory address and the variable’s value.
So what should we prefer when we want to pass a variable to a function? We should use pass by value.
Individual variables are always passed by value. However, arrays, structs, and unions are passed by reference.
Write a C program to demonstrate pass by value.
1. Create a function that takes a variable as an argument.
2. The function should print the variable’s value.
3. Call the function.
4. Modify the variable’s value.
5. Print in the main function the variable’s value.
Here is source code of the C Program to demonstrate pass by value. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to demonstrate pass by Value.
*/
#include <stdio.h>
void swap (int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main ()
{
int a = 10;
int b = 20;
printf ("Before swap, a = %d, b = %d\n", a, b);
swap (a, b);
printf ("After swap, a = %d, b = %d\n", a, b);
return 0;
}
1. Take two numbers as input and store it in the variables a and b respectively.
2. Call the function swap and pass the variables a and b as parameters to the function swap.
3. In function swap, recieve the parameters through variables a and b respectively.
4. Copy the value of variable a to the variable temp. Copy the value of variable b to the variable a and copy the value of variable temp to the variable b. This will do the swapping ONLY in the swap() function, but it will NOT change the value of variables in the main() function.
5. Print the variables a and b in the main function as output and exit.
Example:
Input: a = 10, b = 20;
Output: a = 10, b = 20;
Time Complexity: O(1)
In a pass by value program, only basic input/output and swapping operations are performed, which takes O(1) time.
Space Complexity: O(1)
Since no auxiliary space is required, time complexity is O(1).
“10” and “20” as input for number swapping using pass by value in C.
Before swap, a = 10, b = 20 After swap, a = 20, b = 10
To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.
- Practice Computer Science MCQs
- Check C Books
- Apply for Computer Science Internship
- Practice BCA MCQs
- Check Computer Science Books