14 C++ Return by Reference
14 C++ Return by Reference
A DV E RT I S E M E N T S
In C++ Programming, not only can you pass values by reference to a function but
you can also return a value by reference.
Global variables
#include <iostream>
using namespace std;
// Global variable
int num;
// Function declaration
int& test();
int main()
{
test() = 5;
return 0;
}
int& test()
{
return num;
}
Output
In program above, the return type of function test() is int& . Hence, this
function returns a reference of the variable num .
A DV E RT I S E M E N T S
The return statement is return num; . Unlike return by value, this statement
doesn't return value of num , instead it returns the variable itself (address).
This stores 5 to the variable num , which is displayed onto the screen.
Ordinary function returns value but this function doesn't. Hence, you cannot
return a constant from the function.
int& test() {
return 2;
}
int& test()
{
int n = 2;
return n;
}
A DV E RT I S E M E N T S
Related Tutorials
Tutorials Examples
Join our newsle er for the latest Python 3 Tutorial Python Examples
updates.
JavaScript Tutorial JavaScript Examples
Swi Tutorial
C# Tutorial
DSA Tutorial
Company Apps
Privacy Policy
Contact
Blog
Youtube