About Me

My photo
Bangalore, Karnantaka, India
Hi Frndss... I am Divya Prakash, presently working as an ABAP consultant , simplicity is my Prime Importance n I beleive in " First Deserve then DESIRE ".

Tuesday, October 27, 2009

Can we directly compare two structures using the == operator?

No, you cannot!

The
only way to compare two structures is to write your own function that compares the structures field by field. Also, the comparison should be only on fields that contain data (You would not want to compare the next fields of each structure!).

A byte by byte comparison (say using memcmp()) will also fail. This is because the comparison might fonder on random bits present in unused "holes" in the structure (padding used to keep the alignment of the later fields correct). So a memcmp() of the two structure will almost never work. Also, any strings inside the strucutres must be compared using strcmp() for similar reasons.

There is also a very good reason why structures can be compared directly -
unions!. It is because of unions that structures cannot be compared for equality. The possibility that a structure might contain a union makes it hard to compare such structures; the compiler can't tell what the union currently contains and so wouldn't know how to compare the structures. This sounds a bit hard to swallow and isn't 100% true, most structures don't contain unions, but there is also a philosophical issue at stake about just what is meant by "equality" when applied to structures. Anyhow, the union business gives the Standard a good excuse to avoid the issue by not supporting structure comparison.



If your structures dont have stuff like floating point numbers, pointers, unions etc..., then you
could possibly do a memset() before using the structure variables..


memset (&myStruct, 0, sizeof(myStruct));



This will set the whole structure
(including the padding) to all-bits-zero. We can then do a memcmp() on two such structures.


memcmp (&s1,&s2,sizeof(s1));


But this is very
risky and can end up being a major bug in your code!. So try not to do this kind of memcmp() operations on structures variables as far as possible!

1 comment:

Madhu said...

matter is good but use good font colors its not visible clearly

Pic :)

Pic :)
Look at !!!