Passing Argument to Function :
- In C Programming we have different ways of parameter passing schemes such as Call by Value and Call by Reference.
- Function is good programming style in which we can write reusable code that can be called whenever require.
- Whenever we call a function then sequence of executable statements gets executed. We can pass some of the information to the function for processing calledargument.
Two Ways of Passing Argument to Function in C Language :
- Call by Reference
- Call by Value
Let us discuss different ways one by one –
A.Call by Value :
#include<stdio.h> void interchange(int number1,int number2) { int temp; temp = number1; number1 = number2; number2 = temp; } int main() { int num1=50,num2=70; interchange(num1,num2); printf("\nNumber 1 : %d",num1); printf("\nNumber 2 : %d",num2); return(0); }
Output :
Number 1 : 50 Number 2 : 70
Explanation : Call by Value
- While Passing Parameters using call by value , xerox copy of original parameter is created and passed to the called function.
- Any update made inside method will not affect the original value of variable in calling function.
- In the above example num1 and num2 are the original values and xerox copy of these values is passed to the function and these values are copied into number1,number2 variable of sum function respectively.
- As their scope is limited to only function so they cannot alter the values inside main function.
B.Call by Reference/Pointer/Address :
#include<stdio.h> void interchange(int *num1,int *num2) { int temp; temp = *num1; *num1 = *num2; *num2 = temp; } int main() { int num1=50,num2=70; interchange(&num1,&num2); printf("\nNumber 1 : %d",num1); printf("\nNumber 2 : %d",num2); return(0); }
Output :
Number 1 : 70 Number 2 : 50
Explanation : Call by Address
- While passing parameter using call by address scheme , we are passing the actual address of the variable to the called function.
- Any updates made inside the called function will modify the original copy since we are directly modifying the content of the exact memory location.
Summary of Call By Value and Call By Reference :
Point | Call by Value | Call by Reference |
---|---|---|
Copy | Duplicate Copy of Original Parameter is Passed | Actual Copy of Original Parameter is Passed |
Modification | No effect on Original Parameter after modifying parameter in function | Original Parameter gets affected if value of parameter changed inside function |
No comments:
Post a Comment