Please help me understand the following . coz I feel like there is a lot of contrast regarding the concept of References in C++.
- When I run the following code "https://www.programiz.com/cpp-programming/online-compiler/" :
#include <iostream>
using namespace std;
double & WeeklyHours()
{
double h = 46.50;
double &hours = h;
return h; // Segmentation Fault happens (reasonable)
//return hours; // No Segmentation Fault happens (not reasonable)
}
int main()
{
cout << "Weekly Hours: " << WeeklyHours();
return 0;
}
I get the following output :
/tmp/f1hb0gooH1.o
Segmentation fault
This is reasonable for me, as when trying to print out the variable "that the returned reference is referring to", this variable has already been destroyed and this piece of memory is no longer allocated.
However,
- When I run the following code "https://www.programiz.com/cpp-programming/online-compiler/" :
#include <iostream>
using namespace std;
double & WeeklyHours()
{
double h = 46.50;
double &hours = h;
//return h; // Segmentation Fault happens (reasonable)
return hours; // No Segmentation Fault happens (not reasonable)
}
int main()
{
cout << "Weekly Hours: " << WeeklyHours();
return 0;
}
I get the following output :
/tmp/f1hb0gooH1.o
Weekly Hours: 46.5
This is never reasonable for me.
As far as I know, in function WeeklyHours() hours and h both have the same memory address. And hours doesn't consume any memory address, rather it is just another alias for h .
So, why is the output different in this 2nd case "when returning hours instead of h"?