[comp.lang.c] Initializing bit fields

talvola@janus.Berkeley.EDU (Erik Talvola) (06/27/90)

In article <1656@crabcake> zhu@cs.jhu.edu (Benjamin Zhu) writes:

   In article <7330025@hpcllca.HP.COM> walter@hpcllca.HP.COM (Walter Murray) writes:
   >Scot Mcintosh asks:
   >
   >> Given:
   >> struct {
   >>    int field1:1;
   >> 	       :1;
   >>    int field2:1;
   >>    int field3:1;
   >> 	} var = {0,0,0};
   >
   >> Does ANSI define which field the middle zero initializes, or is this
   >> implementation dependent?
   >
   >"All unnamed structure or union members are ignored during initialization."
   >ANSI 3.5.7 (page 72, line 38)  Thus the middle zero initializes
   >field2.
   >

	   That is what I thought before. However, after I tried this out
	   with my gcc compiler, it turns out that at least gcc is not doing
	   what I expected. Here is an example.

... example deleted ...

	   Guess what's the printout?

	   1 1 0			/* should be 1 1 1 according to ANSI */


I just tried this on GCC 1.37.1 on a Sun 3/50, and it prints out 1 1 1
as according to ANSI-C - maybe you are using an older buggier version
of GCC?



--
+----------------------------+
! Erik Talvola               | "It's just what we need... a colossal negative 
! talvola@janus.berkeley.edu | space wedgie of great power coming right at us
! ...!ucbvax!janus!talvola   | at warp speed." -- Star Drek

kdq@demott.COM (Kevin D. Quitt) (06/29/90)

In article <1656@crabcake> zhu@cs.jhu.edu (Benjamin Zhu) writes:
>>"All unnamed structure or union members are ignored during initialization."
>>ANSI 3.5.7 (page 72, line 38)  Thus the middle zero initializes
>>field2.
>>
>
>	That is what I thought before. However, after I tried this out
>	with my gcc compiler, it turns out that at least gcc is not doing
>	what I expected. Here is an example.
>
>main(void)
>{
>	struct  {
>		unsigned int	field1 : 2;
>		unsigned int	field2 : 2;	/* unsigned int field2 :2, */
>		unsigned int	       : 2;	/*                     :2; */
>		unsigned int	fieldn : 2;
>	}  mask = { 1, 1, 1 };
>
>	printf("%u %u %u\n", mask.field1, mask.field2, mask.fieldn);
>}
>
>	Guess what's the printout?
>
>	1 1 0			/* should be 1 1 1 according to ANSI */

    What version are you running, and on what machine? gcc 1.37.1 on a
Motorola Delta 3000 series (680x0) produces the correct results, as does
the native compiler.  (THAT was a surprise - of course, I had to move the
struct out of the main function and remove the void parameter).


-- 
 _
Kevin D. Quitt         demott!kdq   kdq@demott.com
DeMott Electronics Co. 14707 Keswick St.   Van Nuys, CA 91405-1266
VOICE (818) 988-4975   FAX (818) 997-1190  MODEM (818) 997-4496 PEP last

                96.37% of all statistics are made up.