Return the address of a static const variable in C

Viewed 271

Is it safe to return the address of a static const variable in C like below?

uint8_t *return_static_const_addr(void)
{
    static const uint8_t values[2] = {0x01, 0x02};

    return values;
}
2 Answers

It will have a constant address during the runtime, so, yes it's safe.

The static const variable here is local variable so it would not be stored on the stack and therefore are generally not thread safe. It also depends on the compiler. Returning static const variable would be safe if you were writing this, say for example, for C++11, where such kind of dynamic initialization of a local static is thread-safe.

Related