Re: Mechanics of calculating structure-member offsets



Sensei <senseiwa at Apple's mac dot com> writes:
On 2007-03-02 22:08:47 +0100, Keith Thompson <kst-u@xxxxxxx> said:
And if your implementation doesn't provide offsetof() (it's defined in
<stddef.h>), find a different one. The standard requires offsetof()
to exist; if it doesn't, your implementation is *badly* broken, and
anything else in the language could be missing or broken.

Just a curiosity: is offsetof() required by the standard to be a
#define?

Yes.

Can I check against it by simply using the following code?

#ifndef offsetof
#error .........
#endif

Well, probably. In a conforming implementation, that will just tell
you whether you've #include'd <stddef.h> (and not explicitly undefined
offsetof afterward). In a non-conforming implementation, how do you
know that #ifndef is going to work properly?

It's possible to have a working compiler and a broken <stddef.h>, but
I really don't think there's much point in testing for it (unless
you're writing a conformance test suite). If you need offsetof(),
just go ahead and use it; if it's not defined, you'll get an error
message. (The compiler won't treat it as a call to an external
function because the first argument is a type name.)

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: Multi precision floating point
    ... language extension. ... the offsetof() macro was provided by the quote that I have included ... The standard library macro defined in, ... compiler accepts a program with a syntax error or a constraint violation, ...
    (comp.lang.c)
  • Re: Linux without the GNU toolchain?
    ... >> Did we mention offsetof()? ... And all the sizeof() stuff boils down to ... depend on that aren't mandated by the standard - where to place padding ... this likely isn't of much of a challenge for icc to replicate. ...
    (comp.os.linux.misc)
  • Re: Mechanics of calculating structure-member offsets
    ... santosh wrote: ... The standard requires offsetof() ... anything else in the language could be missing or broken. ...
    (comp.lang.c)
  • Re: Mechanics of calculating structure-member offsets
    ... The standard requires offsetof() ... anything else in the language could be missing or broken. ... Sensei ...
    (comp.lang.c)
  • Re: Can it be done at compile time?
    ... The C standard requires offsetof to be an integer constant expression: ... which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes, to the structure member (designated by member-designator), from the beginning of its structure ...
    (comp.lang.c)