JosephKK said:
[...]
The real problem is that even if copying is done using (possibly an
internal equivalent of) memcpy(), it is quite possible to start out with
two different structs with different padding, and then assign identical
values to the members of those structs, potentially leaving only the
padding different. Any reasonable programmer would expect those two
structs to compare equal; and that requires that the comparison operator
ignores padding, and therefore must know where it is.
Of course, it's easily possible to write an implementation which works
around this by carefully keeping all padding bytes at, say, zero, at all
times. Requiring this of all implementations, though, defeats the
purpose of leaving the value of padding undefined.
Arrgh. Does the standard require struct assignment to work across
implementations?
The first time I read that sentence, I thought you were talking about
assigning a struct in one implementation to a struct in another
implementation; of course the standard doesn't require that. But to
answer the question I think you were asking, yes, the standard
requires each implementation to support struct assignment.
If so, why cannot equals comparison work within an
implementation? Well ordering obviously does not work cleanly.
I thought that was fairly clear from the discussion so far, but ...
The C standard *could* have required equality comparison to work for
structs. The most straightforward way to define it would be that two
structs are equal if their corresponding members are equal; the rule
would be applied recursively for members that are structs. This
breaks down if any of the members are unions; probably comparison of
unions, or of structs containing unions, would be disallowed.
I can think of at least a couple of reasons assignment is required but
equality comparison isn't.
First, assignment is much simpler to implement; all you need is the
equivalent of memcpy(). Comparison would have to ignore any padding
bytes, would have to deal specially with bit fields, and might require
specialized code if pointer and/or floating-point comparison isn't
just bitwise comparison. If you compare two bitwise identical
structs, but they both contain a floating-point member whose current
value is a NaN, are they equal? At the time when struct assignment
was added to the language, struct comparison would have been a
substantial burden on compilers.
Second, struct comparison just isn't all that useful. When was the
last time you really needed to compare two structs for equality? And
even if you did, would the obvious member-by-member comparison really
do what you want? I think it's more common to need to ignore certain
members depending on the values of other members, or to do a deep
comparison that dereferences pointers (and determines whether to
compare just a single element or an array of some size that has to be
computed).