Initialising an union.

Jeroen Dobbelaere Jeroen.Dobbelaere@tvd.be
Wed Aug 19 10:03:00 GMT 1998


Yes, I forgot to say that this is only true for C++

(See http://www.cs.sbcc.net/~shouk/cppdraft/cd2/ for a copy
of the working paper)

(maybe something to add to the faq, although it is not the definitive
standard :( )

I don't know what it should be for C++.

Also note that in your example, you are using an **auto-variable** :

void test() 
{       union x X = { 0 }; 
        for(;;); 
        X.a++; 
} 

It also seems that I mixed up static/global variables and auto :

This is the relevant section for this problem :

 8.5.1  Aggregates                                      [dcl.init.aggr]
[..]

15When  a  union  is  initialized with a brace-enclosed initializer, the
  braces shall only contain an initializer for the first member  of  the
  union.  [Example:
          union u { int a; char* b; };

          u a = { 1 };
          u b = a;
          u c = 1;              // error
          u d = { 0, "asdf" };  // error
          u e = { "asdf" };     // error
    --end example] [Note: as described above, the braces around the ini-
  tializer for a union member can be omitted if the union is a member of
  another aggregate.  ]


It seems not to say anything about the initialization of remaining
bytes. Because those are on the stack, those (probably) wont be
initialized -> so you should explicitly initialize the member you need.


Aurel Balmosan wrote:
> 
[..]
> 
> Well in the ANSI-C books I have this is not defined in this way. It is only
> said that unions can now be initialised (ANSI-C version 2)
> 
> So it seems to not a bug in egcs-1.0.3a but what draft is it? C++ or ANSI-C?
> 
> Bye,
> 
>         Aurel.
> 
> --
> Aurel Balmosan           | Department SE-SW
> ORGA Kartensysteme GmbH  | phone: +49 5254 991 824
> An der Kapelle 2         | fax  : +49 5254 991 749
> 33104 Paderborn, Germany | mailto:ab@orga.com



More information about the Gcc-bugs mailing list