home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!sun-barr!ames!agate!dog.ee.lbl.gov!horse.ee.lbl.gov!torek
- From: torek@horse.ee.lbl.gov (Chris Torek)
- Newsgroups: comp.lang.c
- Subject: Re: initiaklizing union members
- Date: 26 Jul 1992 01:58:00 GMT
- Organization: Lawrence Berkeley Laboratory, Berkeley
- Lines: 57
- Distribution: usa
- Message-ID: <24901@dog.ee.lbl.gov>
- References: <1708@toro.MTS.ML.COM> <5391@dsacg3.dsac.dla.mil>
- Reply-To: torek@horse.ee.lbl.gov (Chris Torek)
- NNTP-Posting-Host: 128.3.112.15
-
- In article <1708@toro.MTS.ML.COM> scott@toro.MTS.ML.COM (Scott Strool)
- writes:
- [given]
- >>struct Row {
- >> int Type;
- >> union {
- >> int ival;
- >> char *sval;
- >> } value;
- >>};
-
- >>how would i set value with a static declaration:
- >>
- >>static Row r0 = { 0, 1234 };
- >>static Row r1 = { 1, "string" };
-
- In article <5391@dsacg3.dsac.dla.mil> nto0302@dsacg3.dsac.dla.mil
- (Bob Fisher) writes:
- >I don't know if this is a compiler problem or a syntax problem. I
- >suggest that you try initializing Row r1 with a pointer, not a string.
- >If that doesn't help, try placing int Type after the union. The union
- >may or may not be aligning on a word boundary.
-
- None of these suggestions are even close.
-
- In ANSI C, only the initializer for r0 is legal. Unions may be
- initialized, but only via the first member. There is no way to
- select some other member in an initializer.
-
- In Classic C, the situation is even worse: Unions can NEVER be
- initialized.
-
- If you have an ANSI C compiler, you can get away with this:
-
- struct Row {
- int Type;
- union {
- int ival;
- char *sval;
- } value;
- };
- struct Row_str {
- int Type;
- union {
- char *sval;
- int ival;
- } value;
- };
- static Row r0 = { 0, 1234 };
- static Row_str r1_str = { 1, "string" };
- #define r1 (*(struct Row *)&r1_str)
-
- If you have a Classic C compiler ... forget it. Use runtime
- initializers.
- --
- In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 510 486 5427)
- Berkeley, CA Domain: torek@ee.lbl.gov
-