Sujet : Re: Results of survey re. a new array size operator
De : jameskuyper (at) *nospam* alumni.caltech.edu (James Kuyper)
Groupes : comp.lang.cDate : 29. Jan 2025, 17:09:39
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vndk9r$2etm7$1@dont-email.me>
References : 1 2 3 4 5 6 7 8
User-Agent : Mozilla Thunderbird
On Wed, 29 Jan 2025 11:45:47 +0000
bart <
bc@freeuk.com> wrote:
On 29/01/2025 09:48, Tim Rentsch wrote:
...
That's a flawed analogy. A macro to compute the number of
elements in an array can be done in standard C. The
functionality of offsetof cannot be done in standard C, and
that's what it needs to be in the standard library.
Can't it? The various versions I've seen, including mine, look like
this:
#define offsetof(a,b) (size_t) &( ((a*)0) -> b)
The semantics of the "->" operator specify that
"The value is that of the named member of the object to which the first
expression points..." (6.5.2.3p4).
There can be no such object, because
"... a null pointer, is guaranteed to compare unequal to a pointer to
any object ..." (6.3.2.3p3).
Since there is no explicitly defined behavior for such an expression,
the behavior is implicitly undefined. On many platforms it will work
exactly as you expect, but not all.
Even on platforms where that part works, this code relies upon the
assumption that the result of that conversion will be the distance from
the beginning of the struct to the start of the specified object. That
seems to be based upon the assumption that a null pointer points at
address 0, and that addresses increase by one for each byte in the
object, and that the conversion to size_t converts a pointer value into
the corresponding address. All of those assumptions are valid on many
platforms, but none of them are guaranteed by the standard. "Any pointer
type may be converted to an integer type. Except as previously
specified, the result is implementation-defined." (6.3.2.3p6). So this
definition for the offsetof() macro, while a valid one on many
platforms, is not standard C.
That's why offsetof() is a standard macro with implementation-specific
expansion - on many platforms, the above expansion won't work.