LEC: 15
Function Parameters and Arguments
||
Call by value and Call by Reference
A function parameter (sometimes called a formal parameter) is a variable declared in the function declaration:
Example :
void function(int i)
{.....}
An argument (sometimes called an actual parameter) is the value that is passed to the function by the caller:
Example :
function(17);
There are 2 ways to pass arguments to a function :
--->1. Call by value
--->2. Call by reference or Call by address
Call BY value:--
- In this we Pass the copy of variable or data to the function.
- The changes doesn't reflect to the original data.
Call BY Reference or call by address:--
- In this we Pass the address of data to the function.
- The changes reflect to the original data.
Source Code for Call By value
#include<iostream> using namespace std; void swap1(int a,int b) //parameters { int temp=a; //temp a b a=b; b=temp; cout<<"Under swapping function \nthe value of a : "<<a<<" and b : "<<b<<endl; } int main() { int x=5,y=7; cout<<"Before function call \nthe value of a : "<<x<<" and b : "<<y<<endl; swap1(x,y); //argument cout<<"After the function call \nthe value of a : "<<x<<" and b : "<<y<<endl; return 0; }
|
|
Source Code for Call By Reference
#include<iostream> using namespace std; void swap1(int a,int b) //parameters { int temp=a; //temp a b a=b; b=temp; cout<<"Under swapping function \nthe value of a : "<<a<<" and b : "<<b<<endl; }
void swap2(int* a,int* b) //parameters { int temp=*a; //temp a b *a=*b; *b=temp; cout<<"Under swapping function \nthe value of a : "<<*a<<" and b : "<<*b<<endl; } int main() { int x=5,y=7; /*--->call by value cout<<"Before function call \nthe value of a : "<<x<<" and b : "<<y<<endl; swap1(x,y); //argument cout<<"After the function call \nthe value of a : "<<x<<" and b : "<<y<<endl; */ cout<<"Before function call \nthe value of a : "<<x<<" and b : "<<y<<endl; swap2(&x,&y); //argument cout<<"After the function call \nthe value of a : "<<x<<" and b : "<<y<<endl; return 0; }
|
|
Comments
Post a Comment