0

I understand that it's undefined to return a reference to a local variable for a function, like:

int& returnIntRef_One()
{
    int value = 5;

    return value;

}

But, in this function:

int& returnIntRef_Two()
{
    int i = 5;
    int &value =i;

    return value;
}

The value seems to be returned fine.

Can someone please explain me what's the difference?

Thank you

Nir.L
  • 87
  • 6

1 Answers1

1

Accessing a dangling reference in any way is undefined behavior. Thus the second example is undefined behavior too. So anything can happen. It may work sometimes, it may crash other times, it may not crash but may give garbage value etc.

In short you must not assume that it will always work and thus you must not use it.

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
taskinoor
  • 45,586
  • 12
  • 116
  • 142