3 Functions
3 Functions
Functions
Prepared By
TCA Gafoor
HSST Computer Application
AKM HSS KOTTOOR
This is the default argument passing method in C++. In this method, the value
contained in the actual argument is passed to the formal argument ie, a copy of the
actual argument is passed to the function. Any) changes made to the formal
argument does not effect actual argument.
Example: Swapping two values using call by value
#include<iostream> void swap(int x,int y)
using namespace std; //function definition
void swap(int,int); {
int t;
//function prototype declaration
t=x;
int main( ) x=y;
{ y=t;
int a=10,b=50; cout<<"The values of x and y are :";
swap(a,b);//function call by value cout<<x<<” “<<y;
cout<<"The values of a and b are :"; }
Working of the above program
cout<<a<<” “<<b;
t=10;
} x=50;
y=10;
Call by reference (Pass by
reference) method
In this method a reference of the actual argument is passed to the function. The
actual argument and formal argument shares the same memory location.
Here any changes made to formal argument effects or is reflected back to the
actual arguments. The formal argument is preceded by) ‘&’ Operator.
Example: Swapping two values using call by reference void swap(int &x,int &y)
#include<iostream> //function definition
using namespace std; {
int main( ) int t;
t=x;
{
x=y;
void swap(int &x,int &y); y=t;
//function prototype declaration }
int a=10,b=50; Before Swapping
cout<<"The values of a and b before swapping:"; After Swapping
cout<<a<<" "<<b; t=10;
x=50;
swap(a,b); //function call by value
y=10;
cout<<"\n"<<"The values of a and b after swapping :";
cout<<a<<" "<<b;
Call by value / reference
Comparison
Scope of variables and function