Formal arguments C++ Programing

Formal arguments - while declaring a function, the arguments list of parameters we specify are known as formal parameters.
Actual arguments - The parameter’s value (or arguments) we provide while calling a function is known as actual arguments.


Example

#include<iostream>

using namespace std;

int sum(int x, int y)
{
    int add = x + y;
    return add;
}

int main()
{
    int a =10;
    int b = 20;

    int add = sum(a, b);

    cout<<add;

    return 0;
}
In the above example,
Variable x and y are the formal parameters or (formal arguments).
Variable a and b are the actual arguments (or actual parameters).
Example

#include<iostream>
using namespace std;

int increment(int var)
{
    var = var+1;
    return var;
}

int main()
{
    int num1 = 20;
    int num2 = increment(num1);

    cout<<"num1 value is: "<<num1<<endl;
    cout<<"num2 value is:"<<num2<<endl;

    return 0;
}

Output
num1 value is: 20
num2 value is:21
Value of variable num1 is 20 even after doing increment operation because function is called by value, which means num1 value gets copied into var and the variable var got incremented (not variable num1), which later stored in num2, via call.

Call by reference

In Call by Reference method the addresses of actual arguments (or parameters) are passed to the formal parameters, which means any operation performed on formal parameters affects the value of actual parameters.
Example

#include<iostream>
using namespace std;

int increment(int  *var)
{
    *var = *var+1;
    return *var;
}
int main()
{
    int num1=20;
    int num2 = increment(&num1);

    cout<<"num1 value is : "<<num1<<endl;
    cout<<"num2 value is : "<<num2<<endl;

    return 0;
}
Output
num1 value is : 21
num2 value is : 21

0 Comments