Why does this char array need to be static?

const char * u8_to_bstr(const uint8_t & u8) {
    static char s[9];   // space for 8-char string
    s[8] = 0;           // terminate string
    char * sp = s;
    for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) {
        cout << s << endl;
        *(sp++) = ((u8 & xbit) == xbit) ? '1' : '0';
    return s;

I encountered this piece of code studying that converts a uint8 to a string representing its binary. My question is, why do we need the static qualifier for static char s[9]? When I remove the static qualifier I get some very strange behavior but I don’t understand why.


The function returns s, which is declared on the stack of this function. Were it not static, it would go out of scope, effectively disappear, once the function returns because all the storage on the stack is made available for reuse once a function returns. By making it static, it’s forced to have a persistent address in memory. However, it’s still bad design – if you call this function from multiple threads, they’ll fight with each other for use of the static memory space.