The following code compiles runs, and usually gives the expected result but it contains a serious flaw. What is this flaw? Why is the program still able to produce the expected result? How can I rewrite both the function, and the calling code, so that the program no longer contains the flaw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
double* average ( double val1 , double val2)
{
double ave = (val1 + val2)/2;
return &ave;
}
int main ()
{
double* ave = 0;
ave = average (2, 3.1);
cout << "The average is " << *ave << endl ;
}
For some reason you are returning to the variable which is destroyed after function execution.
One solution is to make it return by value instead of pointer.
Second is to dynamically alllocate memory
Third to return pointer to the static variable
double* average ( double val1 , double val2)
{
double ave = (val1 + val2)/2;
return &ave; //Returning address to the local varuable
} //ave is destroyer here and any attempt to use returned value is undefined behavior
Correct and most desireable way:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
double average (double val1 , double val2)
{
double ave = (val1 + val2)/2;
return ave;
}
int main ()
{
double ave = average (2, 3.1);
std::cout << "The average is " << ave << std::endl ;
}
The original post is returning the address of a local double variable, that is then deleted once the function returns (and this, as has been said results in undefined behavior).
How does the swap function work?
From what I understand it just swaps the two pointers around.
When you use the function swap(&x, &y), what does this do?