Andrea Loforte
Andrea Loforte

Reputation: 117

returning local variables by reference

i have the following code:

        int& func(int i){
          int *p = &i;
          return *p;
        }

        int& func2(int i){
          vector<int> v;
          v.push_back(i);
          return v[0];
        }

        int & func3(int i){
          array<int,4> arr;
          arr[0] = i;
          return arr[0];
        }

        int& func4(int i){
          int j = i;
          return j;
        }

    int main(){

      cout<<func(3)<<endl;
      cout<<func2(10)<<endl;
      cout<<func3(100)<<endl;
      cout<<func4(123)<<endl;

    return 0;
    }

outuput:
3
0
100
segmentation faul(core dumped)

calling func it's ok because while p is local *p is i ,and i lives in global scope(?). calling func2 return 0, which thing does not make sense to me, i expected to have a segmentation fault since v is a local vector... calling func3 returns the correct value, and this does not make sense either, for the same reason as above. calling func4 finally does what i expected giving segmentatioun fault

can someone help me understand what happens in deep? why are vector and array working as they were declared as static ? in fact considering that all functions are returning reference, i expected to have segmentation fault since vector and array are local object, and they should be deleted once function ends.

very thanks

Upvotes: 0

Views: 285

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57678

If you desire or must return a reference, then use a static variable:

int& my_func(int variable)
{
  static int some_value = 0;
  some_value = variable;
  return some_value;
}

The keyword static tells the compiler that the variable will have a lifetime after execution leaves the function.

To return a reference, you need to refer to a variable that will not disappear after execution leaves a function.

Upvotes: 1

SergeyA
SergeyA

Reputation: 62563

Undefined behavior is happening there. Returning local parameter or variable by reference is undefined behavior, the same way as returning an address to it.

Upvotes: 5

Related Questions