This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Using Compound Literal + type-punning to initialize static const array
- From: Joseph Myers <joseph at codesourcery dot com>
- To: Mason <mpeg dot blue at free dot fr>
- Cc: <gcc-help at gcc dot gnu dot org>, Marek Polacek <polacek at redhat dot com>, Jakub Jelinek <jakub at gcc dot gnu dot org>
- Date: Fri, 28 Nov 2014 16:19:03 +0000
- Subject: Re: Using Compound Literal + type-punning to initialize static const array
- Authentication-results: sourceware.org; auth=none
- References: <54736280 dot 8040409 at free dot fr> <54789EBD dot 9040606 at free dot fr>
On Fri, 28 Nov 2014, Mason wrote:
> On 24/11/2014 17:53, Mason wrote:
>
> > Consider the following code: [big snip]
>
> (Perhaps my previous message was too verbose.)
>
> Why does gcc reject the following code:
>
> union foob { int val; struct { int X; } bits; };
> static const int u = ((union foob) {.bits = { .X=42 }}).val;
>
> $ gcc -std=gnu89 test.c
> test.c:2:30: error: initializer element is not constant
> static const int u = ((union foob) {.bits = { .X=42 }}).val;
For the reason stated in the error message: that initializer is not a
constant expression (it involves access to an anonymous object). There is
a limited allowance in GNU C for when the initializer is a compound
literal of the right type (so that you can define a macro of a structure
or union type that expands to something usable in both assignments and
initializers), but not for any more complicated operations involving them.
--
Joseph S. Myers
joseph@codesourcery.com