why cann't compare the structures?

G

Google Groups

If i take two structures with same members then,why cann't i compare
those two structures?
 
D

DDD

If i take two structures with same members  then,why cann't i compare
those two structures?

You can do it. But you have to write it youself. In c, maybe a
function takes two arguments can solve this problem.

If in C++, you could write a class(struct) like a std::string, and
overload operation such as ==, > and <.

Good luck!
 
C

Chris Dollin

Google said:
If i take two structures with same members then,why cann't i compare
those two structures?

You can't compare them using `==` because the language doesn't
do that.

It probably doesn't do it because (a) it can hide a lot of
operations under an innocent-looking `==` symbol, and C
traditionally doesn't conceal that much activity, and (b) it
isn't clear what the meaning of that `==` should be, and (c)
it's sufficiently easy to write one's own comparison function
that the pressure is off the language.

Re (a), one might think that was good reason to also disallow
assignment. However that seems to be significantly more useful
an operation, is required for passing structures by value (which
is less convenient to do by hand than comparision is), and makes
it a trifle easier for the compiler to generate good code for
copying one struct to another.

Re (b), consider

struct amby { int n; char *cp; } a, b;
...
if (a == b) ...

Presumably you expect the compiler to check that a's and b's
`n` fields are `==`. What about the `cp` fields? How shall it
compare them?

Whichever of the at-least-two ways you suggest, some people
will expect the other. The compiler in general /doesn't know/
what equality should mean on a user-defined data type, and
C (unlike say Pop11, C++, or Java) has no machinery for attaching
a user-defined function to a standard equality test.

Re (c), note the minor complication that it may make a significant
difference how the structs are passed to the comparision function,
by pointer or by value, and the difference is forced to be visible
in the calling code. Unlike (say) C++ or (ISO) Pascal, you can't
change your mind post-hoc without changing all the uses of the
function. Opinions on whether this is a Good Thing or not differ.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top