JC Los Banes JC Los Banes - 10 months ago 43
C++ Question

Why is it needed to declare an array as 'static' when returning it from a function. (C++)

I already know that a 'static' storage class allows a local variable to keep on existing on the duration of the program.

What I would like to know why it is needed to declare the 'digits[3]' array as static. What happens if I don't declare it as static, other than a compiling error.

P.S. I am quite new in handling pointers or memory addresses in C++.

Although I have a bit of an idea on the 'Stack' memory allocation regarding scopes in C++.

int* getDigits(int input)

const int TEN = 10;
int toStore;
int digits[3];
for (int i = 0; i < 3; ++i)
toStore = input % TEN;
digits[i] = toStore;
input = input / TEN;
return digits;

int main(int argc, char const *argv[])
int* ptr;
ptr = getDigits(123);
for (int i = 0; i < 3; ++i)
std::cout << *( ptr+i ) << std::endl;

return 0;

Answer Source

You are returning a pointer to an array which is local to the function. If you declare it as static, it means the lifetime of the array extends until the end of the program, so the calling code can dereference the pointer returned from the function. If you do not declare it as static, it is an "automatic" variable whose lifetime ends when the block (function body) ends, and therefore dereferencing a returned pointer to the data is undefined behavior.

In any case, neither of these things is a typical, correct solution. For one thing, if the function is called twice, the second call may change data pointed to by the first result. A more typical solution is to have the function return a pointer (perhaps shared_ptr or unique_ptr) to an array allocated dynamically using new int[3]. Another solution is to have the function create and return a std::array<int, 3>, which is a proper class type which can be returned by value (only C-style arrays cannot be readily returned by value from a function).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download