Friday, Jan 19th

Last update12:59:40 PM GMT

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

Write e-mail


Structures can only be compared field by field and the only way to do that is to write your own function that does it. Also, the comparison should be only on fields that contain data and not the 'next' fields of each structure''.

A byte by byte comparison (say using memcmp()) will also fail in case of structures as the comparison might pick up random bits present in unused "holes" in the structure (when padding is used, to keep the alignment of the later fields correct). Hence, a memcmp() of the two structures will almost never work. Also, any string inside the structures must be compared using strcmp() for similar reasons.

Structures cannot be compared for equality because of unions. 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 cannot know how to compare two structures. Even though this is a little unlikely
, the presence of unions within structures 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 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.

Share this post

Web Hosting