Re: Copying Aggregate Data Types in C
- From: gordonb.3ondg@xxxxxxxxxxx (Gordon Burditt)
- Date: Thu, 18 Dec 2008 00:30:21 -0600
Yes, provided s1 and s2 are the same struct type. What you cannot
do (because of padding, etc) is compare them for equality. i.e.:
if (s1 == s2) ...
is not legal.
Why does qsort() take a function pointer to a function to compare
elements? One comparison does not fit all.
I'm very surprised at this. I tried it just there with a C compiler
and also with a C++ compiler, and both gave a compiler error. I don't
see why they couldn't have made the comparison result in a comparison
of all members, something like:
#define (a == b) (a.i == b.i && a.j == b.j && a.k == b.k)
Now try doing it with character arrays containing strings.
If the structure has one member char name[10], and a.name contains
"Rebecca\0\0\0" and the b.name contains "Rebecca\0W%", are they
equal? strcmp(a.name, b.name) says yes. a.name == b.name says no,
but that doesn't compare the contents AT ALL. But the array contents
are NOT the same.
Now try doing it with char pointers.
If the structure contains a member char *p, and a.p == "Rebecca"
and b.p == "Rebecca" but the two "Rebecca"s came from different
calls to strdup() [1] are the structures equal? strcmp(a.p, b.p)
says yes. a.p == b.p says NO. The pointers point at the same data
but the pointers are not equal.
Now try doing it with a union as a member of the struct. I don't
know how to approach that.
So if you want to compare two structs for equality (I'm talking value
equality as opposed to binary equality), then you actually have to
verbosely compare member by member? That's a pain.
I'd insist that the compiler generate a warning on any structure
equality test where any of the members is an array, pointer, or
floating-point value. And I'd still rank it as the likely location
of a bug almost regardless of the bug description.
Now if you really want to open cans of worms, after equality you'll
want a >= b operations on structures.
.
- References:
- Copying Aggregate Data Types in C
- From: Jujitsu Lizard
- Re: Copying Aggregate Data Types in C
- From: CBFalconer
- Re: Copying Aggregate Data Types in C
- From: Tomás Ó hÉilidhe
- Copying Aggregate Data Types in C
- Prev by Date: Re: Copying Aggregate Data Types in C
- Next by Date: float() function
- Previous by thread: Re: Copying Aggregate Data Types in C
- Next by thread: Re: Copying Aggregate Data Types in C
- Index(es):
Relevant Pages
|