My question is similar to some related questions, but the answers to these questions do not anwer my main confusion. I try to put the question here in its most simple form.
I want to return an array that is defined inside a function body. As C++ does not allow to return an array by value, I declare the function to be returning a pointer.
Why needs this array to be declared static
inside the function body in order to be accessible in the main program? I know that local variables are destroyed upon exiting the function body, but the function still returns a pointer to this array, no?
float *doubleEachElement(float *arr)
{
static float result[3]; // static keyword is necessary
for (int i = 0; i != 3; i++) result[i] = 2 * arr[i];
return result;
}
int main()
{
float a[3] = {1.0, 2.0, 3.5};
float *a2;
a2 = doubleEachElement(a);
for (int i = 0; i!=3; i++) cout << a[i] << " * 2 = " << *(a2+i) << endl;
// only prints out correctly if the value is declared static inside the function body
return 0;
}