Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 625
billibub Avatar asked Apr 20 '26 07:04

billibub


1 Answers

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.

like image 194
Adrian Mole Avatar answered Apr 22 '26 22:04

Adrian Mole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!