The question is not why and when one should use it. I'm wondering what exactly happens in the inferior level, because we get really curious results doing it.
For example, it is clear when you use it like this:
int& func(int& num) {
++num;
return num;
}
Here we pass a variable by reference, change it, and return a new reference to the same variable.
But what happens if we do this? :
int& func(int num) {
++num;
return num;
}
The variable num
ceases to exist when the function func
is done. C++ does not allow to create references without initializing them with a variable. But in this case, both compilation and execution go without errors. For example, if we don't initialize an int
, we get random behavior:
int num;
std::cout << num; // gives 6422352 or sth like that
But if we initialize it with the function above:
int num1(1);
int num2(func(num1));
cout << num2; // console freezes for a second or two, and execution stops, without any errors
So I've been wondering:
- Why are we not getting a compilation error returning a reference to a non existent object?
- What is this that is assigned to
num2
? - Why does it not cause any execution errors, but just stops the program?