[comp.std.c] Constant expressions in initializers

brunog@cognos.uucp (Bruno Godbout) (03/29/89)

	I need some help with the ANSI definition of a "constant
expression" inside an initializer.  I am trying to compile a
piece of code that is supposed to initialize a structure member with
the value of the "offsetof" macro and the compiler gives me an error.
The error message says that "the initializer must be a constant 
expression".

	I am using a C compiler which is said to be consistent with the
Draft Proposed ANSI standard for C.  The compiler defines the "offsetof"
macro (in <stddef.h>) as follows:

--------

#define offsetof(structype,field) \
		( (size_t)(char *) &(((structype *)0)->field) )

--------

	Here is a simplified example of what I am trying to do:

--------

struct dummy {
	size_t s;
	float f;
	};

struct dummy Dummy = { offsetof(struct dummy,f),
                       2.0 };

--------

	The compiler tells me that "the initializer must be a constant 
expression" and flags the element initialized by offsetof.  I compiled
this code successfully with other compilers.  Thinking that this might
be relevant to ANSI compilers only, I tried it with "gcc -ansi" and with
"gcc -ansi -pedantic" and it still compiled fine.

	I would like to know if this code is rejected by the ANSI
definition or if it is only a restriction of the compiler I am using.

	Thank you for your help.
-- 
Bruno Godbout        3755 Riverside Dr.  VOICE: (613) 738-1338 ext.5086
Cognos, Inc          P.O. Box 9707         FAX: (613) 738-0002
                     Ottawa, Ontario       
	             CANADA  K1G 3Z4      UUCP: uunet!mitel!sce!cognos!brunog

gwyn@smoke.BRL.MIL (Doug Gwyn ) (03/31/89)

In article <5716@cognos.UUCP> brunog@cognos.UUCP (Bruno Godbout) writes:
>	I would like to know if this code is rejected by the ANSI
>definition or if it is only a restriction of the compiler I am using.

It looked okay to me.  This might make a good test case for compiler
validation.  So long as you invoke offsetof() correctly, which it
appears that you did, offsetof() is supposed to expand to an integral
constant expression, which is a subset of "arithmetic constant
expression", which is one of the allowed initializer classes.

shankar@hpclscu.HP.COM (Shankar Unni) (04/01/89)

> struct dummy Dummy = { offsetof(struct dummy,f),
>                        2.0 };

Also try:

   char SmallArray [ offsetof(struct dummy, f) ];

   ...
   struct something {
      int i : offsetof (struct dummy, f);
   };

   ...
   switch (i) {
      case offsetof (struct dummy, f):   break;
   }

   ...
---
Shankar Unni.