Home > Blockchain >  GCC/clang compile error with function-scoped static pointer to unnamed array
GCC/clang compile error with function-scoped static pointer to unnamed array

Time:12-02

Why do GCC and clang show "error: initializer element is not constant" and "error: initializer element is not a compile-time constant" (respectively) when defining a function-scoped static pointer initialized to an unnamed array; but, when defining the same static pointer to the same unnamed array in file-scope they manage just fine.

I have compiled the same program using a compiler for embedded H/W, which compiles without error.

Here is a code snippet with the error active:

int foo()
{
    static int *ptr = (int[]) { 9, 8, 7 }; /* COMPILE ERROR */
    return ptr[2];
}

int main(void)
{
    return foo();
}

And here is a similar code snippet with the static pointer in file scope, which GCC and clang compile without issue:

static int *ptr = (int[]) { 9, 8, 7 }; /* File-scope is fine */

int foo()
{
    return ptr[2];
}

int main(void)
{
    return foo();
}

I can of course define a separate static array inside my function and point my static pointer to that array, but I want to use an unnamed array. I have tried different compiler flags to no avail:

  • -std=c90
  • -std=c99
  • -std=c11
  • -std=gnu11

CodePudding user response:

The problem lies in the scope of the compound literal (i.e. your "unnamed array"); when that is used at file scope (as in your second snippet), then the C Standard specifies that it has static storage duration, so it can be used as an initializer.

However, a compound literal declared at block scope (as in your first example) has automatic storage duration, so it's address cannot be used as an initializer in this context.

From this Draft C11 Standard:

6.5.2.5 Compound literals


5     The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

  • Related