You are on page 1of 4

Return by reference

Allows a function to modify a variable


in the calling program
#include <iostream>
using namespace std;
int num;
int& test();

int main()
{ test() = 5;
cout << num;
return 0;
}

int& test()
{ return num; }

Output: 5
• While returning,
– It should not be a constant
• int& test() { return 2; }
– It should not return a local variable
• int& test() { int n = 2; return n; }
#include <iostream>
using namespace std;
int x;
int& setx();

int main()
{ setx() = 92;
cout << x;
return 0;
}

int& setx()
{ return x; }

Output: 92

You might also like