Explain different ways of calling functions
with appropriate examples
In C++
There are TWO ways of calling functions:
1) Call by Value: In this technique we pass the Value to arguments which are copied into formal parameters of the functions. Hence, the original values are unchanged only parameters inside function changes.
void Add(int x)
{
x = x + 10;
}
int main()
{
int x = 10;
Add(x);
// AS YOU CAN SEE VALUE Of X REMAINS 10
cout << "x: " << x;
// OUTPUT- x: 10
}
2) Call by Reference: In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both case they will change the values of the original value.
void Add(int &x)
{
x = x + 10;
}
int main()
{
int x = 10;
Add(x);
// NOW YOU CAN SEE VALUE OF X CHANGED TO 20
cout << "x: " << x;
// OUTPUT- x: 20
}
Get Answers For Free
Most questions answered within 1 hours.