Methods of Function -Part II

3. Call by Reference in C++

In C++, there is a way for passing values to function arguments called “call by reference.” When a function is called by reference, the formal parameter receives a reference to the actual parameters, which means that modifying the function’s internal values will also change the parameters’ actual values. The following is an illustration of the call by reference approach:

#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

4. C++’s default arguments

If we don’t provide our value as a parameter, the function will utilise the default arguments. Writing default arguments after other arguments is advised.

Using the default argument as an example

int sum(int a = 5, int b);

5. C++ Constant Arguments

When you don’t want your values to be altered by the function, you should use constant parameters. To make the parameters unmodifiable, use the const keyword.

An illustration utilising a constant argument,

int sum(const int a, int b);
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