Summary
It is up to your personal preference or otpimization choice which one to use, but as I'll explain below, the two obvious choices are
- compare the instances of the structures field-by-field
- compare the instances of the structures by their memory content byte-by-byte (using memcmp)
Field-by-field Comparison
You can compare structures by comparing their fields one-by-one, just as you did in your example. It is straightforward and easily readable and understandable of what happens.
Memory Comparison
An alternative solution would be to use memcmp to compare two instances of the same structure. Since they are of the same type, they take the same amount of memory so you can compare their memory byte-by-byte:
#include <stdio.h>
#include <string.h>
typedef struct
{
char firstName[50];
char lastName[50];
unsigned short int yearOfBirth;
unsigned char monthOfBirth;
unsigned char dayOfBirth;
} Person;
int main()
{
Person JohnDoe = { "John", "Doe", 1997, 10, 4 };
Person JohnDoe2 = { "John", "Doe", 1997, 10, 4 };
Person JaneDoe = { "Jane", "Doe", 2004, 3, 18 };
printf("%d\n", memcmp(&JohnDoe, &JohnDoe2, sizeof(Person)) == 0); // This prints 1 - true (they are the same)
printf("%d\n", memcmp(&JohnDoe, &JaneDoe, sizeof(Person)) == 0); // This prints 0 - false (they are different)
return 0;
}
Optimization Considerations
We could just use memcmp all the time. Right? So why would we ever choose to compare field-by-field?
Well, memcmp goes through the structure's memory from start to end and compares it with the other. However, one can easily come up with a structure, where (for some reason) different data usually is around the end of the structure. Let's imagine John Doe is a common name (or we can call on the Smiths or Carpenters, you name them). Comparing the first and the last name (as memcmp would do with out structures above) would be a "waste of time" as it would probably still match.
However, if our Person structure would have some unique ID, such as Social Security Number or similar, that's different for every person, then you can just compare that one first via the field-by-field comparison, then the next field that would most probably differ (e.g. year). While, if the SocialSecurityNumber is the last field in our structure, it would be compared last and memcmp would take longer to work out the differences than our manual filed-by-field comparison.
Of course, you could move the SocialSecurityNumber to be the first field in the structure, but you do not always want to re-order your structures.
In a normal pet-project you do not have to worry about these optimizations though. And there are other ways too (e.g. crating a hash and comparing the hash first, and only comparing the actual content when the hashes match).