Programming Tutorials

Call by reference in C++ Functions

By: Babbar Ankit in C++ Tutorials on 2009-05-30  

In C++, passing arguments to functions can be done either by value or by reference. Passing by reference allows a function to modify the value of the argument passed to it.

To pass an argument by reference, we use the & operator in the function definition. Here's an example:

#include <iostream>
using namespace std;

void increment(int& num) {
    num++;
}

int main() {
    int num = 10;
    cout << "num before increment: " << num << endl;
    increment(num);
    cout << "num after increment: " << num << endl;
    return 0;
}

In the above code, the increment function takes an integer num as a reference argument. Inside the function, the value of num is incremented by 1. When we call the increment function with num as its argument, the value of num is changed.

Output:

num before increment: 10
num after increment: 11

Passing by reference is useful when we want to modify the value of a variable inside a function, without having to return the modified value.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)