Your two examples are both flawed. The fact a compiler allows you to do something doesn't mean you should do it (although most compilers, if configured to picky warning levels, will issue warnings about the problems).
The first version falls off the end of the function, so the caller will exhibit undefined behaviour if it tries to use the return value.
The second function returns a reference to an argument passed by value. Since an argument passed by value ceases to exist when the function return, the caller will also exhibit undefined behaviour when it attempts to use the returned reference.
An example that would demonstrate the usage of references would be
Code:
int &biggest(int &x, int &y)
{
return (x >= y ? x : y); // this selects the biggest of x and y, and returns a reference to it
}
int main()
{
int a = 5, b = 7;
biggest(a,b) = 32; // b is larger, so this sets b to be 32.
int p = 16, q = 2;
biggest(p, q) = 32; // p is larger, so this statement sets p to 32
return 0;
}
Pointers can be used in similar ways, albeit the syntax is different. There are also the same caveats - a function should not return the address of a local variable, nor should it return a pointer to a argument passed by value.