Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 4 Aug 1998 18:27:34 -0400 (EDT)
From:      Thomas David Rivers <rivers@dignus.com>
To:        chuckr@glue.umd.edu, Nicolas.Souchu@prism.uvsq.fr
Cc:        freebsd-hackers@FreeBSD.ORG
Subject:   Re: C and static initialization with unions
Message-ID:  <199808042227.SAA16749@lakes.dignus.com>
In-Reply-To: <Pine.BSF.4.00.9808041508210.409-100000@picnic.mat.net>

next in thread | previous in thread | raw e-mail | index | archive | help
Chuck Robey <chuckr@glue.umd.edu> wrote:

> On Tue, 4 Aug 1998, Nicolas Souchu wrote:
> 
> > Hi there,
> > 
> > A question about C and static initialization of unions:
> > 
> > suppose,
> > 
> > union foo_t {
> > 	int i;
> > 	char c;
> > 	void *p;
> > };
> > 
> > static union foo_t bar = { (void *)&anyvar };
> > 
> > The compiler says "warning, making integer from pointer without a cast"...
> > Which is true and could lead to bad asm code.
> > 
> > Is there a way to do this properly? Should I forgive unions or what else?
> 
> No, you forgot to mention which union memeber to use.  Your foo_t.p
> would do nicely.

 You can't in C initialize only a member of a structure that way.

 Furthermore, the ANSI C standard specifies that initializations of unions
 use the first field of the union as the initialization type.

 Thus, gcc is correct in its message; since the type of the initialization
 for the union field would be and int, the first field of the union.

 Now; if you reorder the union fields, so that 'p' is first, you can
 do the initialization you'd like without any problems.

 Another posted also responded with the appropriate casts for doing that.

 Also - you should be aware that ANSI forbids assigning to one element
 of a union and referencing a different element.   (Basically, the
 'type-punning' problem) C compilers are allowed to optimize field 
 references based on type; so that:

 main() 
 {
  union foo_t foo;
  void *vp;

  foo.i = 5;
  foo.p = 0;

  if(foo.i) {
	printf("true\n");
  } else {
	printf("false\n");
  }
 }

 may, depending on the optimizer, print either true or false.   Technically,
 this is an invalid ANSI C program.

	- Dave Rivers -

> 
> > 
> > -- 
> > Nicolas.Souchu@prism.uvsq.fr
> > FreeBSD - Turning PCs into workstations - http://www.FreeBSD.org
> > 
> > To Unsubscribe: send mail to majordomo@FreeBSD.org
> > with "unsubscribe freebsd-hackers" in the body of the message
> > 
> > 
> 
> ----------------------------+-----------------------------------------------
> Chuck Robey                 | Interests include any kind of voice or data 

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199808042227.SAA16749>