Methods of function-Part I

Now, there are methods using which arguments are sent to the function. They are,

1. Call by Value in C++

In C++, call by value is a way for passing values to function parameters. In the case of call by value, copies of the actual parameters are passed to the formal parameter, therefore changing the values within the function has no effect on the actual values.

The call by value method is demonstrated in the following example:

#include <iostream>
using namespace std;
 
void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
}
 
int main()
{
    int x = 5, y = 6;
    cout << "The value of x is " << x << " and the value of y is " << y << endl;
    swap(x, y);
    cout << "The value of x is " << x << " and the value of y is " << y << endl;
}

Output:

The value of x is 5 and the value of y is 6

The value of x is 5 and the value of y is 6

2.Call by Pointer in C++

In C++, a pointer call is a way for passing values to function parameters. In the case of a pointer call, the address of the actual parameters is provided to the formal parameter, which means that if we modify the values inside the function, the actual values will change.

Here’s an example of a call by pointer method in action:

#include <iostream>
using namespace std;
 
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
int main()
{
    int x = 5, y = 6;
    cout << "The value of x is " << x << " and the value of y is " << y << endl;
    swap(&x, &y);
    cout << "The value of x is " << x << " and the value of y is " << y << endl;
}

Output:

The value of x is 5 and the value of y is 6
The value of x is 6 and the value of y is 5
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in