Parameter Passing Techniques in C
Notes:
Parameter Passing Techniques in C Programming Language:
Pass by value , Pass by reference , Call by value , Call by reference in C:
Parameter passing mechanism in C:
A process of transmitting the value of a variable or address of a variable from one function to another function is called as parameter passing mechanism.
There are 2 ways in which we can pass parameters from one function to another function:
1. Pass by value or Call by value
2. Pass by reference or Call by reference
Pass by value or Call by value:
- means while calling a function value of a variable is passed
- i.e. while calling a function value of the actual parameter is copied into the formal parameter
Actual parameter:
- is a parameter which is passed while calling a function
Formal parameter:
- is a parameter which is written within a function definition
Note: while passing parameters by value; actual parameters do not get affected
Example Code:
#include<stdio.h>
void swap(int,int);
int main()
{
int num1=1,num2=2;
printf("Before swap num1=%d and num2=%d\n",num1,num2); // 1 and 2
swap(num1,num2);
printf("After swap num1=%d and num2=%d",num1,num2); // 1 and 2
return 0;
}
void swap(int num1,int num2)
{
int temp=0;
temp= num1;
num1=num2;
num2=temp;
}
Pass by reference or Call by reference:
- means while calling a function address of a variable is passed
- i.e. while calling a function address of the actual parameter is copied into the formal parameter
Actual parameter:
- is a parameter which is passed while calling a function
Formal parameter:
- is a parameter which is written within a function definition
Note:
- while passing parameters by reference; actual parameters can be affected
- if we want to use the value of an actual parameter in some other function, then we take help of pass by value
- if we want to modify the value of an actual parameter in some other function, then we take help of pass by reference
Example Code:
#include<stdio.h>
void swap(int *,int *);
int main()
{
int num1=1,num2=2;
printf("Before swap num1=%d and num2=%d\n",num1,num2); // 1 and 2
swap(&num1,&num2);
printf("After swap num1=%d and num2=%d",num1,num2); // 2 and 1
return 0;
}
void swap(int *num1,int *num2)
{
int temp;
temp= *num1;
*num1=*num2;
*num2=temp;
}