Returning by reference

Is there a way to return by reference in a function, for example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<stdio.h>

using namespace std;

int sum(int num1, int num2)
{
    return num1 + num2 ;
}

int main()
{
    int num1, num2, s;
    cout<<"\nEnter two numbers: ";
    cin>>num1>>num2;
    s = sum(num1, num2);
    cout<<"\nSum of "<<num1<<" and "<<num2<<" is "<<s;
    return 0;
}


Can the above fumction be modified so that the result is returned by reference method?Thank you.
A function can return a reference to an object, and also a function can modify an argument passed by reference. Here's one that does both:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int& acc(int& num1, int num2)
{
    return num1 += num2;
}

int main()
{
    cout << "\nEnter two numbers: ";
    int num1, num2;
    cin >> num1 >> num2;
    cout << "\nSum of " << num1 << " and " << num2 << " is ";
    int& s = acc(num1, num2);
    cout << num1 << " also accessible as " << s << '\n';
}

int& sum(...) but that shouldn't compile since you're returning an rvalue.
@Cubbi

So a function can return by reference if i use the hampersand symbol before s anfd its datatype? Thanks for your help.
closed account (zb0S216C)
There's something you should be aware of when returning L-value references: don't return temporary storage, like this:

1
2
3
4
5
int &Function( )
{
  int X;
  return( X ); // Oops.
}

Once "Function( )" returns, "X" will be popped from the stack, thereby leaving the reference returned by the function in an invalid sate and attempting to access the referent is undefined behavior.

A simple solution is to declare "X" as static.

1
2
3
4
5
int &Function( )
{
  static int X;
  return( X ); // OK
}

Since static storage declared within functions remains even after the function has finished, returning a reference to the aforementioned storage is deemed safe due to the extended lifetime of the storage. However, since the static storage is only directly accessible to the function in which the storage is declared, the reference becomes the only means of access once the function has ended.

Wazzak
Last edited on
Topic archived. No new replies allowed.