I thought the function readRef() returns a reference to num, so i can change the value of through that reference. But, it's not happening. Effectively, there's no difference between these two functions, then. But, it can't be. I would be very thankful to the guy(s) who explain where i was wrong.
The first version returns a reference to num. num stops to exist when the function ends so the caller never gets a chance to read the value of num. It might look like it works but it is undefined behaviour so anything is allowed to happen.
The second version returns a copy of num so this is safe.
Here the reference returned by calling the function remains valid because the object it's pointing to (some element of data) remains in existence after the function returns.
#include <iostream>
int & crazy(int &i)
{
return i;
}
int main()
{
int i=43;
crazy(i) += 57;
std::cout << i << std::endl;
}
100
Edit: I apologize for my hasty comment. I now realize that sathya691 edited the original post after Cubbi replied.
Well sathya, when you do not use references, the variables you return or parameters you input are copies. Which is why, if you forget the & in int &num, you'll have a dangling reference as soon as the function ends.