Is there a way to compare structures automatically?
C Interview Questions and Answers
(Continued from previous question...)
Is there a way to compare structures automatically?
No. There is not a good way for a compiler to implement structure comparison (i.e. to support the == operator for structures) which is consistent with C's low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused ``holes'' in the structure (such padding is used to keep the alignment of later fields correct; ). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. Any compiler-generated comparison could not be expected to compare pointer fields appropriately in all cases: for example, it's often appropriate to compare char * fields with strcmp rather than == .
If you need to compare two structures, you'll have to write your own function to do so, field by field.
(Continued on next question...)
Other Interview Questions
|