Search code examples
cgccvisual-c++c99

Initializing variables with a compound literal


The following code cannot be compiled when put inside a scope/function, the compiler will produce an error stating something along the lines of initializer element is not constant. This happens on GCC as well as MSVC.

static const char * const * const list = (const char *const[]){ "abc", "def", "xyz" }; 

But when the code is put outside of any function and list is initialized as a global variable with static storage duration, the code compiles fine and doesn't produce any warnings or errors. Only when list is non-static, it can be initialized within a scope/function as well.

The following quote from the cppreference docs has caught my eye:

The unnamed object to which the compound literal evaluates has static storage duration if the compound literal occurs at file scope and automatic storage duration if the compound literal occurs at block scope (in which case the object's lifetime ends at the end of the enclosing block).

Does this mean that it's safe to say that local variables with a static storage duration cannot be initialized with a compound literal?


Solution

  • Objects with static storage duration can be initialized by constant expressions. Compound literals are not constants (in fact they are lvalues). You can't initialize objects with static storage duration with compound literals (though GCC allow it as extension).